The iterator design pattern
Surfing channels on a TV acts as a stress buster for me. Switching channels back and forth is so soothing. This process of visiting channels in an order is called iteration. When we are in a hotel room, away from home, the aired channels may be different. However, the process of iteration remains the same. We visit a channel, we may spend some time watching it, and if we feel bored again, we go to the next one.
In programming, visiting each element of a data structure is routinely required. To make itself iterable, the data structures produce an iterator object. The iterator object needs to obey a contract that is laid down by the interface. For example, if the data structure produces an instance of java.lang.Iterable
, then we can use Java's foreach
loop to visit each element, that is, we can iterate the data structure. Let's look at the following figure:
The following Java code snippet shows how we can iterate various data structures...