package rebelsky.list; /** * An array-based implementation of simple lists. * * @author CSC152 2004F */ public class ArrayBasedSimpleList implements SimpleList { // +--------+------------------------------------------------------------ // | Fields | // +--------+ /** * The values in the list. */ Object[] contents; /** * The number of values in the list. */ int n; // +--------------+------------------------------------------------------ // | Constructors | // +--------------+ /** * Build a new empty list. */ public ArrayBasedSimpleList() { this.contents = new Object[3]; this.n = 0; } // ArrayBasedSimpleList // +---------+----------------------------------------------------------- // | Methods | // +---------+ /** * Add object addMe somewhere in the list. * * @post * The list now contains an additional copy of addMe. */ public void add(Object addMe) { // Warning! We have not yet handled arrays that fill. if (this.contents.length == this.n) { Object[] bigger = new Object[this.contents.length*2]; for (int i = 0; i < this.contents.length; i++) { // copy contents at position i bigger[i] = this.contents[i]; } this.contents = bigger; } this.contents[this.n] = addMe; ++this.n; } // add(Object) /** * Get a new cursor for the list. */ public Cursor getCursor() { return new ArrayBasedCursor(this); } // getCursor() /** * Get a new cursor for the list. */ public SimpleCursor getSimpleCursor() { return new ArrayBasedSimpleCursor(this); } // getCursor() /** * Remove the object last returned by cursor c. */ public void remove(SimpleCursor c) { // The thing to remove is at c.p - 1. (Problem if at start of list, but // fails precondition.) We shove the last thing there. this.contents[((ArrayBasedSimpleCursor) c).p - 1] = this.contents[this.n-1]; this.contents[this.n-1] = null; this.n--; } // remove(SimpleCursor) /** * Convert this list to a string for ease of printing. */ public String toString() { // Special case: Empty list. if (this.n == 0) return "[]"; String result = "["; for (int i = 0; i < this.n-1; i++) result = result + this.contents[i].toString() + " "; result = result + this.contents[this.n-1]; result = result + "]"; return result; } // toString() } // class ArrayBasedSimpleList