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. |
Home Trees The Iterator Class | ||
The Iterator Class
Iterator is an abstract class in the java.util package. It specifies three methods:
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 (iterator.next ()); }
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.
|
||
Home Trees The Iterator Class |