//******************************************************************** // ArrayIterator.java // // An iterator over the elements of an array. //******************************************************************** import java.util.Iterator; import java.util.NoSuchElementException; public class ArrayIterator implements Iterator { private int current; // the current position in the iteration private T[] array; //----------------------------------------------------------------- // Sets up the iterator using the given array //----------------------------------------------------------------- public ArrayIterator (T [] array) { this.array = array; this.current = 0; } //----------------------------------------------------------------- // Returns true if this iterator has at least one more element // to deliver in the iteraion. //----------------------------------------------------------------- public boolean hasNext() { return (current < array.length); } //----------------------------------------------------------------- // Returns the next element in the iteration. If there are no // more elements in this itertion, a NoSuchElementException is // thrown. //----------------------------------------------------------------- public T next() { if (! hasNext()) throw new NoSuchElementException(); current++; return array[current - 1]; } //----------------------------------------------------------------- // The remove operation is not supported //----------------------------------------------------------------- public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } public static void main(String[] args) { Integer [] array = new Integer[5]; for (int i=0;i itr = new ArrayIterator(array); while (itr.hasNext()){ System.out.println(itr.next()); } } }