// A Seq // // The Seq stores a sequence of objects // // We can: - add an object to the end of the sequence // - ask for the i^{th} object in the sequence // - ask for the length of the sequence // - insert an object inside the sequence // - delete an object from inside the sequence import java.util.*; interface Seq { public void append( Object o ); public Object elementAt( int pos ); public int getLength(); public void insert( int pos, Object o ); public void delete( int pos ); } // Usually the interface and implementation would be in // different files, but not in this example. public class mySeqWithIterator implements Seq { private Object [] data; // array to store objects private int capacity; // size of array private int length; // number of stored objects // Constructors mySeqWithIterator( int initialCapacity ) { length = 0; capacity = initialCapacity; data = new Object[ initialCapacity ]; } mySeqWithIterator() { // default Seq has capacity 10 this( 10 ); } // Iterator class private class mySeqIterator implements Iterator { private int nextIndex; mySeqIterator() { nextIndex = 0; } public boolean hasNext() { return (nextIndex < length); } public Object next() throws NoSuchElementException { if (nextIndex >= length) throw new NoSuchElementException(); Object obj = data[ nextIndex ]; nextIndex++; return obj; } public void remove() throws UnsupportedOperationException, IllegalStateException { throw new UnsupportedOperationException(); } } public mySeqIterator createIterator() { return new mySeqIterator(); } // Return the length of the sequence public int getLength() { return length; } // Append an object to the end of the sequence public void append( Object o ) { if (length == capacity) { // Double the size of the array Object [] newData = new Object[ capacity + 100 ]; for (int j=0; j length) { System.out.println( "Seq::elementAt: position " + pos + " is outside the range [0," + (length-1) + "]" ); System.exit(1); } // Get the object return data[pos]; } // Insert an Object at a particular position public void insert( int pos, Object o ) {} // Delete an Object at a particular position public void delete( int pos ) {} public static void main( String [] args ) { Random rand = new Random(1231432); mySeqWithIterator s = new mySeqWithIterator(); // Fill up the Seq System.out.println( "Filling up:" ); for (int i=0; i<10; i++) { int x = rand.nextInt(100); s.append( new Integer(x) ); System.out.print( " " + x ); } System.out.println( "" ); // Iterate over the Seq Iterator iter = s.createIterator(); System.out.println( "Iterating over:" ); while (iter.hasNext()) System.out.print( " " + iter.next().toString() ); System.out.println( "" ); } }