Design pattern: Iterator


The Iterator pattern is a design pattern that use an iterator to traverse and selects objects in a sequence without the necessity of knowing the underlying structure of the sequence. It is especially useful when we work with complex data structures.

Iterator is the simplest implementation of Java iterators. The ListIterator designed for List has more functions. It can traverse the List from two directions, and can also insert and delete elements from the List.



  • Aggregate: Interface that defines the structure of the classes that can be iterated.

  • ConcreteAggregate: Implementation of the data structure that we want to iterate.

  • IIterator: Interface that defines the structure of the iterators.

  • ConcreteIterator: Implementation of an iterator, which inherits from IIterator.


The Iterator function in Java is relatively simple :

(1) Use the method iterator() to require the container to return an Iterator. The first time the Iterator’s next() method is called, it returns the first element of the sequence.

Note: The iterator() method is a java.lang.Iterable interface that is inherited by Collection.

(2) Use next() to get the next element in the sequence.

(3) Use hasNext() to check if there are any more elements in the sequence.If there are more elements we return to step two, this is repeated until the end.