design patterns ·

Iterator

Provides a way to sequentially access elements of a collection without exposing its underlying structure.

easy0.5hgeneraljava
Ask GPTConfidence

Theory

Explanation

Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.

When client code needs to traverse a collection without caring how it is stored (array, tree, hash), the Iterator pattern provides a uniform hasNext()/next() interface that works the same for any collection.

Iterator defines hasNext() and next(). The collection implements Iterable, returning a new Iterator instance. The iterator maintains a cursor position and advances it on each next() call. Java's for-each loop uses Iterator transparently.

When to use

Uniform traversal over different collection types - custom data structures, tree/graph traversal, lazy sequence generation.

When not to

Simple arrays or lists where a standard for loop is clearer. When you don't need to hide the collection structure.

Key insights

  • Java's Iterable/Iterator interfaces are a built-in implementation of this pattern
  • For-each loop syntax (for T item : collection) requires Iterable<T>
  • External iterators (client calls next()) vs internal iterators (collection calls a lambda) are two variants
  • Generators in Python and async iterators in JavaScript are Iterator pattern implementations