JMU
The Iterator Pattern
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Looping and Aggregates

Looping Over an Array

javaexamples/iterator/ArrayExample.java (Fragment: 1)
       String    city;

       for (int i=0; i < cities.length; i++)
       {
          city = cities[i];
          System.out.println(city);
       }
        
Looping and Aggregates (cont.)

Looping Over an ArrayList

javaexamples/iterator/ArrayListExample.java (Fragment: 1)
       String    city;

       for (int i=0; i < cities.size(); i++)
       {
          city = cities.get(i);
          System.out.println(city);
       }
        
Looping and Aggregates (cont.)

Looping Over a Linked Structure

javaexamples/iterator/LinkedListExample.java (Fragment: 1)
       Node<String>      current;
       String            city;

       current = first;
       while (current != null)
       {
          city = current.value;
          System.out.println(city);
          current = current.next;
       }
        
Some Observations
Important Operations
The Iterator Pattern

In UML:

images/iterator.gif
Examples in Java
Examples in Java (cont.)
images/collections_java_parameterized.gif

Note that the Map java.util.Map interface does not extend Iterable or Collection, but one can get a Set or Collection object from a Map.

Benefits of the Iterator

What code must change to use a HashSet instead of an ArrayList?

    Iterable<String>    cities;

    cities = new ArrayList<String>();

    // Important code

    // An example loop
    Iterator<String>    i = cities.iterator();
    while (i.hasNext())
    {
       String city = i.next();
       System.out.println(city);
    }
    
Benefits of the Iterator (cont.)
The "New" Loop