Iterator Pattern
What you'll learn: How to traverse a collection's elements without exposing its internal structure using the Iterator Pattern.
The Core Problem
Imagine a library where books are stored in different ways—some on shelves (arrays), others in card catalogs (linked lists), and rare manuscripts in a vault (tree structures). You want to read through each book without needing to know how they're organized. The Iterator Pattern solves exactly this: it provides a uniform way to step through elements of any collection, regardless of how that collection stores its data internally.
How It Works
The Iterator Pattern defines a separate object (the iterator) that knows how to traverse a specific collection. The collection provides a method to create an iterator, and the iterator offers standard operations like:
hasNext(): Check if more elements existnext(): Retrieve the next elementreset(): Return to the beginning (optional)
The client code uses the iterator without knowing whether it's walking through an array, linked list, or tree. This decouples traversal logic from the collection's internal representation.
Why It Matters
Without this pattern, client code would need if-else branches for each collection type, tightly coupling your code to implementation details. The Iterator Pattern lets you swap collection implementations without breaking client code—you've already learned how patterns like Decorator and Adapter promote flexibility; Iterator does the same for traversal.
You've also seen the Template Method Pattern, which defines algorithm structure while letting subclasses customize steps. Iterator similarly standardizes how you access elements while letting each collection implement traversal its own way.
When to Use
Use Iterator when you need multiple simultaneous traversals of the same collection, want to hide complex data structures, or need a uniform interface across different collection types.
Key Takeaway: The Iterator Pattern provides sequential access to collection elements through a standardized interface, hiding the collection's internal structure and enabling flexible, maintainable traversal code.