// variant of MyArray, using an anonymous inner class for the iterator import java.util.Iterator; import java.util.NoSuchElementException; import java.awt.Point; public class MyArray3 { /* internal array to actually hold the data */ private E [] internalArray; // the constructor public MyArray3 (int n) { internalArray = (E[]) new Object[n]; // unfortunately this doesn't work due to current Java limitations: // internalArray = new E[n]; } public int length() { return internalArray.length; } // get an element public E at(int i) { return internalArray[i]; } // set an element public void set(int i, E value) { internalArray[i] = value; } // return an iterator for this array public Iterator iterator() { return new Iterator() { private int index = 0; public E next() { E temp; if (!hasNext()) throw new NoSuchElementException("no next element available"); temp = internalArray[index]; index++; return temp; } public boolean hasNext() { return index < internalArray.length; } public void remove() { /* this is an optional operation - we don't support it */ throw new UnsupportedOperationException("remove operation not supported"); } }; } public static void main(String[] args) { MyArray3 a = new MyArray3(2); a.set(0, new Integer(50)); a.set(1, new Integer(100)); // we can have several iterators active at once on an instance // of MyArray Iterator iter1 = a.iterator(); Iterator iter2 = a.iterator(); while(iter1.hasNext()) { System.out.println(iter1.next()); } while(iter2.hasNext()) { System.out.println(iter2.next()); } } }