Course contentsShow
← Software Engineering
Lesson 295 of 1,9339. Behavioral Design PatternsFree lesson

The Iterator Pattern: Traversing Collections

Learn how Iterator decouples traversal logic from collection structures, enabling uniform access to elements.

The Iterator Pattern: Traversing Collections

What you'll learn: How the Iterator pattern separates the logic of traversing a collection from the collection's internal structure.

The Core Problem

Imagine you have different collections—arrays, linked lists, trees, hash tables—and you need to access each element one by one. Without the Iterator pattern, you'd need to know each collection's internal structure: use indices for arrays, follow pointers for linked lists, perform tree walks for trees. This creates tight coupling between your code and the collection's implementation.

What the Iterator Pattern Does

The Iterator pattern provides a standard way to traverse any collection without exposing how it stores elements internally. It introduces an iterator object that knows how to walk through a specific collection, presenting a uniform interface regardless of the underlying structure.

Think of it like a museum tour guide. Whether the museum's exhibits are arranged chronologically, by theme, or randomly throughout floors, the guide (iterator) gives you a consistent experience: "here's the next item." You don't need to understand the museum's floor plan.

Key Components

An iterator typically provides these operations:

  • hasNext() or isDone() – checks if more elements exist
  • next() – returns the current element and advances
  • Optionally: reset() to start over, current() to peek without advancing

The collection creates and returns iterators when requested. Each iterator maintains its own position, so multiple iterations can happen simultaneously on the same collection.

Why This Matters

By decoupling traversal from the collection structure, you gain flexibility. The collection can change its internal implementation without breaking client code. Clients use the same iterator interface whether they're traversing an array or a complex tree structure.

Key Takeaway: The Iterator pattern separates how you traverse a collection from what the collection is, providing uniform access to elements while keeping collection internals hidden.