The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.

The Iterator Class

Iterator is an abstract class in the java.util package. It specifies three methods:

Does this iteration have more elements?
Return the next element, or throw an exception if there is none.
Remove from the collection the last element that was returned.

The following example uses an iterator to traverse and print the elements of a vector.

        Iterator iterator = vector.iterator ();
        while (iterator.hasNext ()) {
            System.out.println ( ());

Once the Iterator is created, it is a separate object from the original Vector. Subsequent changes in the Vector are not reflected in the Iterator. In fact, if you modify the Vector after creating an Iterator, the Iterator becomes invalid. If you access the Iterator again, it will cause a ConcurrentModification exception.

In a previous section we used the Visitable abstract class to allow a client to traverse a data structure without knowing the details of its implementation. Iterators provide another way to do the same thing. In the first case, the provider performs the iteration and invokes client code to "visit" each element. In the second case the provider gives the client an object that it can use to select elements one at a time (albeit in an order controlled by the provider).

As an exercise, write a concrete class named PreIterator that implements the Iterator interface, and write a method named preorderIterator for the Tree class that returns a PreIterator that selects the elements of the Tree in preorder.

Last Update: 2005-11-21