Iterator Pattern

Iterator Pattern

The iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container’s elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.

For example, the hypothetical algorithm SearchForElement can be implemented generally using a specified type of iterator rather than implementing it as a container-specific algorithm. This allows SearchForElement to be used on any container that supports the required type of iterator.

Java

Java has an Iterator interface that the Collections should implement in order to traverse the elements of the collection. Classic implementations were using the next() method, which is the same for the Java interface. However, there are no currentItem(), first(), and isDone() methods defined. Instead, the Java interface adds the hasNext() and remove() methods.

Leave a Reply

Your email address will not be published. Required fields are marked *