What are the internals of the Iterator pattern?
Answer
The Iterator pattern defines two key interfaces: Iterator (with hasNext(), next(), and optionally remove()) and Iterable/Aggregate (with createIterator()). The concrete iterator holds a reference to the collection and a current position cursor. When next() is called, it returns the current element and advances the cursor. Importantly, the iterator is stateful and independent from the collection — you can have two iterators on the same collection traversing at different speeds simultaneously. In Java, the for-each loop desugars to an iterator call. For tree collections, you can have different iterator implementations for pre-order, in-order, and post-order traversal without changing the tree class.
Previous
How does the Facade pattern differ from Mediator?
Next
What are practical use cases for the Memento pattern?
More Design Patterns (Gang of Four) Questions
View all →- Intermediate What is the Template Method design pattern?
- Intermediate What is the Visitor design pattern?
- Intermediate What is the difference between Factory Method and Abstract Factory?
- Intermediate When should you NOT use design patterns?
- Intermediate How are the Gang of Four patterns categorized?