ProblemYou 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. SolutionUse the Iterator interface. DiscussionIf 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 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 IteratorDemo, the previous ArrayList demo rewritten to use an Iterator to access the elements of the data structure: import java.util.List; import java.util.ArrayList; import java.util.Iterator; /** Iterator used to walk through a List. * @version $Id: ch07.xml,v 1.5 2004/05/04 20:11:49 ian Exp $ */ public class IteratorDemo { public static void main(String[] argv) { List l = new ArrayList( ); StructureDemo source = new StructureDemo(15); // Add lots of elements to the list... l.add(source.getDate( )); l.add(source.getDate( )); l.add(source.getDate( )); int i = 0; Iterator it = l.iterator( ); // Process the data structure using an iterator. // This part of the code does not know or care // if the data is an an array, a List, 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 create our own Iterator in Recipe 7.13. |