Data-Independent Access with Iterators

Problem

You want to write your code so that users don’t have to know whether you store it in an Array, a Vector, an ArrayList, or even a doubly linked list of your own choosing.

Solution

Use one of the Iterator interfaces.

Discussion

If you are making collections of data available to other classes, you may not want the other classes to depend upon how you have stored the data, so that you can revise your class easily at a later time. Yet you need to publish a method that gives these classes access to your data. It is for this very purpose that the Enumeration and later the Iterator interfaces were included in the java.util package. These provide a pair of methods that allow you to iterate, or step through all the elements of a data structure without knowing or caring how the data is stored. The newer Iterator interface also allows deletions, though classes that implement the interface are free either to implement the use of deletions or to throw an UnsupportedOperationException.

Here is IterDemo, the previous Vector demo rewritten to use an Iterator to access the elements of the data structure:

Vector v = new Vector( ); Enumeration e; StructureDemo source = new StructureDemo(15); // Add lots of elements to the Vector... v.addElement(source.getDate( )); v.addElement(source.getDate( )); v.addElement(source.getDate( )); // Process the data structure using an iterator. int i = 0; Iterator it = v.iterator( ); // Remaining part of the code does not ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.