Freitag, 13. Juli 2007

Quicklist class

I found this QuickList class to be very useful for passing dynamic parameters to functions without using Vectors and the likes:




/**
* Simple class for generating lists.
*
* QuickList differs from the List Collection in as much as once created,
* a QuickList does
* not change. New elements are added to a QuickList by creating a
* new QuickList which includes both the new element and the old QuickList.
*
* This makes QuickList suitable for generating low-overhead
* temporary data structures (amongst other things).
*/
public class QuickList {

/**
* All elements in this QuickList apart from the first
*/
private QuickList tail;
/**
* The first element in this QuickList
*/
private Object head;

/**
* Empty Quicklist. Add to the empty QuickList in order to generate a new list
*/
public static final QuickList EMPTY = new QuickList(null, null);

/**
* Creates a new instance of QuickList.
*
* @param tail A list to which a new item is being appended
* @param head a new item to append to a list
*/
protected QuickList(QuickList tail, Object head) {
this.head = head;
this.tail = tail;
}

/**
* Adds an item to a list.
*
* Note that this method does not change this list, but instead returns a
* new list with the new item added to it.
*
* @param item An item to add to the list
* @return A new list with item added to the front
*/
public QuickList add(Object item) {
return new QuickList(this, item);
}

/**
* Get the first item in this list.
*
* @return the first item in this list
*/
public Object head() {
return head;
}

/**
* Get the rump of this list (everything except the first item).
*
* @return A list including all items except the first
*/
public QuickList tail() {
return tail;
}

/**
* Calculate the size of a QuickList
*
* @return Number of elements in this quicklist (not counting EMPTY element)
*/
public int size() {
if (this == EMPTY) return 0;
else return tail.size() + 1;
}
}



To copy this code, please open the source of this page and copy it (STRG+C) from there.

Keine Kommentare: