// An array-like class (written with generics). // Similar to MyArray, except that it uses ArrayList import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; import java.awt.Point; public class MyArray2 { /* internal array to actually hold the data */ private ArrayList internalArray; // the constructor public MyArray2 (int n) { internalArray = new ArrayList(n); } public int length() { return internalArray.size(); } // get an element public E at(int i) { return internalArray.get(i); } // set an element public void set(int i, E value) { internalArray.set(i, value); } /** * inner class for the iterator */ class MyIterator implements Iterator { int index; MyIterator() { index = 0; } public E next() { E temp; if (!hasNext()) throw new NoSuchElementException("no next element available"); temp = internalArray.get(index); index++; return temp; } public boolean hasNext() { return index < internalArray.size(); } public void remove() { /* this is an optional operation - we don't support it */ throw new UnsupportedOperationException("remove operation not supported"); } } /** * return an iterator for this array */ public Iterator iterator() { return new MyIterator(); } public static void main(String[] args) { MyArray2 a = new MyArray2(2); a.set(0, new Integer(50)); a.set(1, new Integer(100)); Iterator it = a.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } }