We use iterators in software projects all the time. When we traverse a list or go through the items of a set or a map, we use an iterator.
Note
The iterator design pattern provides a way to access the elements of an aggregate object (collection) in a sequential manner without exposing the underlying representation of the items. The developer doesn't need to know whether there is a linked list, array, tree, or a hash map underneath.
Using the iterator design pattern, we can create our own objects that act as collections and we can use them in the foreach
loops. In Java, there is an interface called Iterator
, which we can implement for this purpose. In Scala, we can mix in the Iterator
trait and implement its hasNext
and next
methods.
For the class diagram and the example, let's have a ClassRoom
class that will support a foreach
loop running through all students. The following figure shows our class diagram:
We've decided our ClassRoom
class to implement...