The Iterator Pattern

The iterator pattern allows the client code to traverse data collections without exposing their structure. The client code does not need to know how the data are stored, and how to go from one element to another.

This pattern usually defines an Iterator class which keeps a reference to the current element and is able to go to the next element. Java has its Iterator interface that many collection classes implement.

Iterator<Car> it = mylist.iterator(); // retrieve iterator object from the collection
while (it.hasNext()) { // browse all the elements
   Car car = it.next(); // return the current element and move on the next element
   // ... do something
}

Leave a comment

Design a site like this with WordPress.com
Get started