Skip to Main Content
Java Cookbook
book

Java Cookbook

by Ian F. Darwin
June 2001
Intermediate to advanced content levelIntermediate to advanced
888 pages
21h 1m
English
O'Reilly Media, Inc.
Content preview from Java Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Practical Cloud-Native Java Development with MicroProfile

Practical Cloud-Native Java Development with MicroProfile

Emily Jiang, Andrew McCright, John Alcorn, David Chan, Alasdair Nottingham
Distributed Computing in Java 9

Distributed Computing in Java 9

Raja Malleswara Rao Malleswara Rao Pattamsetti

Publisher Resources

ISBN: 0596001703Supplemental ContentCatalog PageErrata