© APSIS GmbH
, Polling,
2000
Polymorphe Implementierung der Schnittstelle Stapel aus der Bibliothek für das Lehrbuch Programmieren mit Java
Dokumentation
Programmtext mit Dokumentation
package lehrbuch.kapitel9;
public class StapelPol implements lehrbuch.kapitel9.Stapel {
public StapelPol(final int groesse) {
inhalt = new Object[groesse];
entleeren();
}
public StapelPol(final StapelPol quelle) throws VollAusnahme {
this(quelle.inhalt.length);
kopieren(quelle);
}
public void entleeren() {
spitze = -1;
}
public void eintragen(final Object element) throws VollAusnahme {
try {
spitze++; // nächster freier Platz
inhalt[spitze] = element; // throws IndexOutOfBoundsException, wenn spitze = inhalt.length
} catch(IndexOutOfBoundsException ausnahme) {
spitze--; // zurücksetzen
throw new VollAusnahme();
}
}
public Object lesen() throws LeerAusnahme { // requires !istLeer()
try {
return inhalt[spitze]; // letztes eingetragenes Element
// throws IndexOutOfBoundsException, wenn spitze = -1
} catch(IndexOutOfBoundsException ausnahme) {
throw new LeerAusnahme();
}
}
public void entfernen() throws LeerAusnahme {
try {
attrappe = inhalt[spitze]; // throws IndexOutOfBoundsException, wenn spitze = -1
spitze--; // Platz des letzten eingetragenen Elements freigeben
} catch(IndexOutOfBoundsException ausnahme) {
throw new LeerAusnahme();
}
}
private static Object attrappe; // global, damit der Compiler es nicht wegoptimiert
public boolean istLeer() {
return spitze == -1;
}
public boolean istVoll() {
return spitze == inhalt.length-1;
}
public void kopieren(final Stapel quelle) throws VollAusnahme {
try {
StapelPol q = (StapelPol)quelle;
inhalt = new Object[q.inhalt.length]; // neue Reihung erzeugen (evtl. alte verlieren)
spitze = q.spitze;
for (int index = 0; index < spitze; index++)
inhalt[index] = q.inhalt[index];
} catch (OutOfMemoryError ausnahme) {
throw new VollAusnahme();
}
}
public boolean istGleich(final Stapel stapel) {
StapelPol s = (StapelPol)stapel;
if (spitze != s.spitze)
return false;
for (int index = 0; index < spitze; index++)
if (inhalt[index] != s.inhalt[index])
return false;
return true;
}
private Object[] inhalt; private int spitze; }
© APSIS GmbH
, Polling,
2000