StringList:Javakurs
Zielsetzung
Eine Klasse, die eine Liste von Textzeilen verwaltet.
Die Umsetzung erfolgt mit einer doppelt verlinkten Liste:
_________________ _________________ _________________ | text: Zeile 1 | | text: Zeile 2 | | text: Zeile 3 | | pred: <null> | <-------|--: pred | <-------|--: pred | | succ: --|-------> | succ: --|-------> | succ: <null> | |_________________| |_______________| |_______________|
Jedes Element hat einen Verweis auf das vorherige und das nachfolgende Element. Im ersten Element ist der Vorgänger null, im letzten Element der Nachfolger.
Die Klassen
class Element {
String text = null;
Element pred = null;
Element succ = null;
}
/**
* Implements a doubled linked list of strings.
*/
public class StringList {
/**
* @param args
*/
public static void main(final String[] args) {
final StringList list = new StringList();
list.add("hello");
list.add("all");
list.add("worlds");
}
private Element first = null;
private Element last = null;
private int count = 0;
/**
* Adds a text to the end of the list.
*
* @param text
* text to append
*/
void add(final String text) {
final Element element = new Element();
element.text = text;
if (this.last == null)
this.last = this.first = element;
else {
element.pred = this.last;
this.last.succ = element;
}
this.count++;
}
/**
* Gets the text of the n-th element of the list.
*
* @param index
* index of the wanted element
* @return <code>null</code>: wrong index<br>
* otherwise: the text of the element with index <code>index</code>
*/
String get(final int index) {
Element element = this.first;
for (int ix = 0; element != null && ix < index - 1; ix++)
element = element.succ;
return element == null ? null : element.text;
}
/**
* @return the count
*/
public int getCount() {
return this.count;
}
/**
* @return the first
*/
public Element getFirst() {
return this.first;
}
/**
* @return the last
*/
public Element getLast() {
return this.last;
}
}