Iterator Pattern

An Iterator is an object that holds a position in a collection and answers one question: is there a next element, and what is it. The aggregate hands out the iterator and keeps its storage private, so callers walk the data without learning whether it is an array, a tree, or a page cursor over a remote source.

💡 Aggregate = the pattern’s name for whatever holds the elements – the playlist, the directory, the deck. The aggregate owns the data; the iterator owns the position.

Why this matters: most machine-coding problems hand you a collection and then ask for a second way to walk it – shuffle a playlist, deal from a shoe, find files under a directory, replay a partition from offset 42. Candidates who have not met the pattern put a getSongs() on the aggregate and an if (shuffle) in every caller. The seam is what gets graded: did traversal become an object, or leak into the client.


Prerequisites

  • Composite Pattern – the structure most interview iterators walk; the tree must exist before the walk is interesting
  • Strategy Pattern – the same seam of one interface and swappable implementations, which is why these two get confused
  • Collections and Complexity – fail-fast iteration and modCount are library behaviour you must be able to explain

The Problem: the caller indexes into your storage

A playlist that exposes its list, and the next-track handler that grew on top of it:

public class Playlist {
    private final ArrayList<Song> songs = new ArrayList<>();

    public void add(Song song) { songs.add(song); }

    public ArrayList<Song> getSongs() { return songs; }   // the whole problem
}

// Caller code -- the next-track button handler, with the mode as flags
private int index = 0;
private boolean shuffle = false;
private boolean repeatOne = false;

public Song next() {
    ArrayList<Song> songs = playlist.getSongs();
    if (songs.isEmpty()) return null;
    if (repeatOne) return songs.get(index);
    if (shuffle) {
        index = new Random().nextInt(songs.size());   // may repeat, may skip
        return songs.get(index);
    }
    if (index + 1 >= songs.size()) return null;
    return songs.get(++index);
}

Three things are wrong, and all three come up in review:

  1. The storage choice is now public API. The return type is ArrayList<Song>, so Playlist can never move to a LinkedList, a deduplicating LinkedHashSet, or a lazily paged source. Even narrowing the declared type to List breaks callers.
  2. It hands out a live mutable reference to internal state. Any caller can do playlist.getSongs().clear(), so Playlist cannot defend one invariant – not “no duplicates”, not “notify listeners on change”.
  3. Ordering lives in the caller, so every caller reimplements it. The download queue, the play-all endpoint and the cast path all need this method, the copies drift, and this one is already wrong: nextInt can play a song three times and never reach another.

The fix is not a better getSongs(). It is to return a position in the collection instead of the collection.


Class Diagram

classDiagram
    class Iterable {
        <<interface>>
        +iterator() Iterator~Song~
    }
    class PlaylistIterator {
        <<interface>>
        +hasNext() boolean
        +next() Song
    }
    class Playlist {
        -List~Song~ songs
        -int version
        +iterator() PlaylistIterator
        +shuffled(long seed) PlaylistIterator
        +repeatOne(Song song) PlaylistIterator
    }
    class SequentialIterator {
        -int cursor
        -int expectedVersion
    }
    class ShuffleIterator {
        -List~Song~ snapshot
        -int cursor
    }
    class RepeatOneIterator {
        -Song song
    }

    Iterable <|.. Playlist
    Playlist --> PlaylistIterator
    PlaylistIterator <|.. SequentialIterator
    PlaylistIterator <|.. ShuffleIterator
    PlaylistIterator <|.. RepeatOneIterator

Note where state sits: version is on the aggregate and expectedVersion on the iterator, so the collection counts its own edits while a cursor only remembers what it saw. And three factories return the same interface, so “shuffle” is decided once at traversal time instead of re-checked every tick.


Real-World Example: Playlist with Sequential, Shuffle and Repeat-One

// The traversal contract -- no lists, indexes or sizes anywhere in it.
// Extending Iterator<Song> is what lets Playlist be Iterable<Song>.
public interface PlaylistIterator extends Iterator<Song> {
    boolean hasNext();
    Song next();
}

// 1) Sequential -- index order, fail-fast if the playlist is edited under it.
class SequentialIterator implements PlaylistIterator {
    private final Playlist owner;
    private final List<Song> songs;      // live view, deliberately
    private final int expectedVersion;
    private int cursor = 0;

    SequentialIterator(Playlist owner, List<Song> songs) {
        this.owner = owner;
        this.songs = songs;
        this.expectedVersion = owner.version();
    }

    @Override public boolean hasNext() { return cursor < songs.size(); }

    @Override public Song next() {
        if (owner.version() != expectedVersion) {
            throw new ConcurrentModificationException("edited mid-traversal");
        }
        if (!hasNext()) throw new NoSuchElementException();
        return songs.get(cursor++);
    }
}

// 2) Shuffle -- walks a permutation, so every song plays once per cycle.
class ShuffleIterator implements PlaylistIterator {
    private final List<Song> snapshot;   // own copy, so later edits cannot bite
    private int cursor = 0;

    ShuffleIterator(List<Song> songs, long seed) {
        this.snapshot = new ArrayList<>(songs);
        Collections.shuffle(snapshot, new Random(seed));
    }

    @Override public boolean hasNext() { return cursor < snapshot.size(); }

    @Override public Song next() {
        if (!hasNext()) throw new NoSuchElementException();
        return snapshot.get(cursor++);
    }
}

// 3) Repeat-one -- hasNext is always true. Once ordering is an object, an
//    unbounded traversal is just another implementation.
class RepeatOneIterator implements PlaylistIterator {
    private final Song song;
    RepeatOneIterator(Song song) { this.song = song; }
    @Override public boolean hasNext() { return true; }
    @Override public Song next() { return song; }
}

// The aggregate. Implementing Iterable<Song> is what makes for-each work.
public class Playlist implements Iterable<Song> {
    private final List<Song> songs = new ArrayList<>();
    private int version = 0;             // bumped on every structural change

    public void add(Song song) { songs.add(song); version++; }
    int version() { return version; }    // package-private: for iterators only

    /** Factory method -- the caller gets a cursor and never the list. */
    @Override public PlaylistIterator iterator() {
        return new SequentialIterator(this, songs);
    }
    public PlaylistIterator shuffled(long seed) { return new ShuffleIterator(songs, seed); }
    public PlaylistIterator repeatOne(Song song) { return new RepeatOneIterator(song); }
}

// for-each compiles to iterator plus hasNext plus next.
for (Song song : playlist) player.play(song);

// One player loop, three orderings, zero flags.
PlaylistIterator order = shuffleOn ? playlist.shuffled(System.nanoTime())
                                   : playlist.iterator();
while (order.hasNext()) player.play(order.next());
import random
from typing import Iterator

class SequentialIterator:
    """Classic external iterator: __iter__ returns self, __next__ advances."""

    def __init__(self, owner: "Playlist", songs: list["Song"]) -> None:
        self._owner = owner
        self._songs = songs                 # live view, deliberately
        self._expected_version = owner.version
        self._cursor = 0

    def __iter__(self) -> "SequentialIterator":
        return self

    def __next__(self) -> "Song":
        if self._owner.version != self._expected_version:
            raise RuntimeError("playlist edited mid-traversal")
        if self._cursor >= len(self._songs):
            raise StopIteration
        self._cursor += 1
        return self._songs[self._cursor - 1]

class Playlist:
    def __init__(self) -> None:
        self._songs: list["Song"] = []
        self.version = 0

    def add(self, song: "Song") -> None:
        self._songs.append(song)
        self.version += 1

    def __iter__(self) -> Iterator["Song"]:
        return SequentialIterator(self, self._songs)

    # A generator is the idiomatic Python form: same external-iterator
    # protocol, but __iter__, __next__ and the cursor are written for you.
    def shuffled(self, seed: int | None = None) -> Iterator["Song"]:
        order = list(self._songs)           # snapshot, immune to later edits
        random.Random(seed).shuffle(order)
        yield from order

    def repeat_one(self, song: "Song") -> Iterator["Song"]:
        while True:                         # unbounded, and still a valid one
            yield song

for song in playlist:                       # uses __iter__ then __next__
    player.play(song)
#include <cstddef>
#include <vector>

class Playlist {
    std::vector<Song> songs_;

public:
    void add(Song song) { songs_.push_back(std::move(song)); }

    // Input-iterator shaped: dereference, advance, compare. Those three
    // operators are the whole contract a range-based for loop needs.
    class SequentialIterator {
        const std::vector<Song>* songs_;
        std::size_t cursor_;

    public:
        SequentialIterator(const std::vector<Song>* songs, std::size_t cursor)
            : songs_(songs), cursor_(cursor) {}

        const Song& operator*() const { return (*songs_)[cursor_]; }
        SequentialIterator& operator++() { ++cursor_; return *this; }
        bool operator!=(const SequentialIterator& other) const {
            return cursor_ != other.cursor_;
        }
    };

    // begin and end are the C++ spelling of implementing Iterable.
    SequentialIterator begin() const { return {&songs_, 0}; }
    SequentialIterator end() const { return {&songs_, songs_.size()}; }

    // A shuffle traversal is a second class of exactly this shape: it owns a
    // shuffled copy of songs_ and steps a cursor over that copy, exposing the
    // same three operators. See the Java tab for the full version.
};

// The compiler expands this into begin then operator!= then operator* then ++.
for (const Song& song : playlist) player.play(song);

Iterator is where ordering lives

In the bad version next() had a flag per mode and a branch per flag, and every new mode added another. Once traversal is an object those branches become classes and the player’s loop stays while (order.hasNext()) forever. Which is why Iterator and Strategy look identical in code: one interface, several implementations, picked at runtime. The only difference is the cursor, so an iterator is a traversal strategy that carries a position. In Music Player the overlap is literal – PlayMode is tagged Strategy and implemented as an iterator.

The trap: what if the playlist is edited mid-traversal? Java’s ArrayList iterator is fail-fast – the list keeps a modCount, the iterator records it at construction, and next() throws ConcurrentModificationException the instant the two disagree. That is the version / expectedVersion pair above.

💡 Fail-fast iterator = one that throws the moment it notices the collection changed underneath it, rather than quietly returning wrong or skipped elements. Learn more →

It is a bug detector, not a thread-safety guarantee, and it fires on single-threaded code just as readily – for (Song s : playlist) if (s.isExplicit()) playlist.remove(s); is the classic, and Iterator.remove() is the one mutation that keeps expectedModCount in step. Nor is fail-fast the only contract: weakly consistent iterators (ConcurrentHashMap) never throw and may or may not reflect a mid-walk edit, while snapshot iterators (CopyOnWriteArrayList) walk the array that existed at iterator() time.

Pick deliberately. A subscriber list wants the snapshot: in PubSub a handler can unsubscribe itself mid-fan-out, and on a fail-fast list that aborts the whole publish. Copy-on-write lets the loop finish over the array it started with, so the departing subscriber may get one last message instead of everyone after it getting none.


Iterator vs Composite vs Visitor vs Streams

Pattern Intent Tell
Iterator Walk an aggregate without exposing how it stores elements A cursor somewhere, plus hasNext / next
Composite Let a container and a leaf share one interface It defines the shape; the tree exists before anyone walks it
Visitor Add an operation across a fixed set of node types One method per node type – visit(File), visit(Directory)
Streams and generators Internal iteration, where the library runs the loop You pass a function in and never call next() yourself

One sentence to keep them apart: Composite defines the tree, Iterator defines the walk over it, Visitor defines what happens at each node. They compose rather than compete – FileSystem has all three, with File and Directory as the Composite, find() as an iterator over that tree, and a later disk-usage pass as a Visitor.

External vs internal, because this is the most common follow-up. With an external iterator the caller owns the loop: you call hasNext() and next(), so you can stop halfway, advance two traversals in lockstep, or hand the cursor to another method and resume later. With an internal iterator the library owns the loop and you supply only the body – playlist.forEach(player::play), or a Stream pipeline. Internal reads better and lets the library fuse stages, stay lazy or go parallel; external is the only one that walks two playlists together or survives across calls.

💡 External iterator = the caller drives the loop with hasNext and next. Internal iterator = you hand the library a function and the library drives the loop.


When to Use vs When to Avoid

Use Iterator When Avoid When
The aggregate’s storage must stay private It is already Iterable and plain order is enough
More than one meaningful order exists over the data There is one order and it will not change
Traversal is lazy or unbounded – paged results, an event feed It all fits in memory and callers want index access
The structure is a tree or graph and the walk carries state A plain for loop over an index reads more clearly
Several traversals must run independently over one aggregate You would be re-implementing ArrayList.iterator()

The characteristic failure mode is writing an Iterator for something already Iterable: thirty lines of cursor, bounds check and hasNext around an ArrayList, reproducing list.iterator() exactly. It happens because the candidate wanted one more pattern on the class diagram, and it reads as not knowing the standard library – which costs more than the pattern earns. See Over-Engineering for the general shape of it. Implement Iterable and delegate, then write a real iterator class only when the traversal has state the list does not: a permutation, a lazily expanded subtree, a page cursor, an offset you intend to persist.


Interview Questions

  1. “External or internal iterator – which do you reach for?” – External when the caller needs control: early exit on a condition the library cannot express, two traversals advancing together, or a cursor that outlives the method that created it. Internal when the loop body is the only interesting part, because then the library can fuse stages, stay lazy or go parallel. The tell that you have thought about it is naming Spliterator – Java’s internal Stream is built on an external splittable primitive, so the two are layers, not rivals.

  2. “What happens if the collection is modified during iteration?” – It depends on the collection’s documented contract, and naming all three is the answer. Fail-fast (ArrayList, HashMap): the iterator compares a recorded modCount and throws ConcurrentModificationException – a bug detector, not a concurrency guarantee, and it fires on single-threaded code too. Weakly consistent (ConcurrentHashMap): never throws, may or may not show the edit. Snapshot (CopyOnWriteArrayList): walks the array that existed at iterator() time. To remove inside a loop, use Iterator.remove().

  3. “Iterate a tree lazily, without materializing the node list.” – Replace the recursion with an explicit stack inside the iterator; that is the whole trick. hasNext() is “stack not empty”, and next() pops a node, pushes its children and returns it. Memory is O(depth) for depth-first instead of O(n) for a collected list, and a caller that stops at the first match never touches the rest of the tree. FileSystem’s find() is this shape – the recursive version is shorter but cannot be paused, which is what “stream me the first 20 matches under a two-million-file root” exposes.

  4. “Do Python generators and C++20 ranges make Iterator obsolete?” – They retire the boilerplate, not the pattern. A generator is an external iterator: it has __iter__ and __next__, and the compiler writes the cursor and the resume points for you. Ranges and views are the same idea with lazy composition on top. What survives is the interface decision – Playlist returning a cursor instead of its list is a choice no language feature makes for you. Where the language helps, write yield rather than a class.


See It in Action

  • Music Player – PlayMode is a traversal cursor: sequential, shuffle and repeat behind one interface
  • File System – find() walks the composite tree with its own stack instead of recursing and collecting
  • PubSub System – a consumer offset is a durable iterator position into a partition, and the subscriber list wants snapshot iteration
  • Deck of Cards – dealing is traversal: one cursor over a shuffled multi-deck shoe, reshuffling at the cut card