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 Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s