Iterator Pattern

Any meaningful application deals with a chunk of data. The data is often in form of a collection of related data elements. We often need to work on each of these elements. The iterator pattern helps us do this.

This problem is not so very pronounced when we are working with Lists - because they can be indexed. We can simply access each element of the list using its index

for (int i=0; i

But, when we work on sets or maps, it is not possible to index them directly. The Iterator Pattern helps us in such a case.

Essentially, the collection defines an "Iterator" - an object that can dish out individual element in the collection - one at a time. Anyone who needs to access each of these elements, can just invoke the iterator object.

The Iterator pattern works through these players

  • Iterator Interface: This interface defines two methods hasNext() and next(). The first method tells us if the iterator has more than it has already given. The next() dishes out the next element in it.
  • Concrete Iterator: This provides an actual implementation for the above methods. Note that the iterator does not maintain a copy of the source collection. It just provides a way to access the contents of the collection.
  • Aggregate Interface: Defines the method to createInterface(). This should return an instance of the iterator
  • Concrete Aggregate: This implements the createInterface() method.
Iterator iterator = list.createIterator();

while (iterator.hasNext()) {;