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 know or care
// if the data is an an array, a Vector, or whatever.
while (it.hasNext(  )) {
    Object o = it.next(  );
    System.out.println("Element " + i++ + " = " + o);
}

To demystify the Iterator and show that it’s actually easy to build, we’ll create our own Iterator in Section 7.15.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.205.235