LLD

Behavioral Patterns

Iterator pattern

When callers need to walk through a collection in different ways, give each way of walking its own object and keep the collection's insides private. We build a music playlist that plays in order, shuffled and on repeat, first by handing out the list and then with iterators.

A music app has a playlist and three buttons: play, shuffle and repeat. The phone app, the car stereo and the smart speaker all play the same playlist. Each of them needs the next song, one at a time, in whichever order the listener picked.

Many programs walk a collection like this: search results a page at a time, every file in a folder tree, tasks in round-robin order. The caller wants "the next one" and should not need to know how the collection stores its items or keeps its place.

The Iterator pattern puts each way of walking into its own object. In this article we build a playlist twice. The first version hands its list to every caller, and each caller writes its own loop. The second gives out iterators. Then we look at what the pattern costs and how it shows up in interviews.

All the code is Java. Every snippet without a Sketch label is cut from a project that compiles: the first-version snippets from the hand-out-the-list version, the rest from the finished design. Both projects run, and the page shows what each one printed. The Open file button on a finished-design snippet shows the whole file in a code browser.

The playlist we are building

A playlist holds songs in the order they were added. The same song may appear twice. The playlist must:

  1. Play in order, from the first song to the last.
  2. Shuffle: play every song exactly once in a random order, with every order equally likely.
  3. Repeat all: play in order, then start again from the first song, without end.
  4. Look the same to every caller. A caller writes one loop and it works for all three modes. No caller sees the list inside the playlist or keeps an index into it.
  5. Never skip or repeat a song by accident when the playlist changes while a walk is going on.
  6. Allow several walks at once, each with its own place, such as the phone shuffling while the car plays in order.
One playlist, three walks
The playlist holds five songs in the order they were added. In order plays them first to last and stops. Shuffle plays each one exactly once, in a random order, and stops. Repeat all plays them in order and starts again from the first song, so it never stops on its own. The caller writes the same loop for all three.The playlist holds five songs in the order they were added. In order plays them first to last and stops. Shuffle plays each one exactly once, in a random order, and stops. Repeat all plays them in order and starts again from the first song, so it never stops on its own. The caller writes the same loop for all three.
The playlist stays the same. Only the order of the walk changes. The playlist holds five songs in the order they were added. In order plays them first to last and stops. Shuffle plays each one exactly once, in a random order, and stops. Repeat all plays them in order and starts again from the first song, so it never stops on its own. The caller writes the same loop for all three.

This figure is the one to draw first in an interview. It separates the collection, which is one list, from the walks, which are many. Each walk has its own order and its own place, and none of them changes the playlist.

The first version: hand the list to every caller

The obvious version gives the playlist a getter that returns its list:

Playlist.javalines 4–14 of 14
public class Playlist {    private final List<Song> songs = new ArrayList<>();     public void add(Song song) {        songs.add(song);    }     public List<Song> getSongs() {        return songs;    }}

Every caller then writes its own loops. The phone app shuffles the list it was given:

PhoneApp.javalines 19–25 of 33
    public void playShuffled(Playlist playlist) {        List<Song> songs = playlist.getSongs();        Collections.shuffle(songs, random);        for (int i = 0; i < songs.size(); i++) {            System.out.println("    phone: " + songs.get(i).title());        }    }

The car stereo shuffles in its own way, by picking a random index for each song:

CarStereo.javalines 11–17 of 30
    public void playShuffled(Playlist playlist) {        List<Song> songs = playlist.getSongs();        for (int i = 0; i < songs.size(); i++) {            Song song = songs.get(random.nextInt(songs.size()));            System.out.println("    car: " + song.title());        }    }

Here is what the first version does with five songs. Step 3 removes every song by Tara Sen with an index loop. Step 4 asks for repeat-all on an empty playlist:

$ java Main
1. The car shuffles:
    car: Last Bus Home
    car: Monsoon Drive
    car: Monsoon Drive
    car: Chai at Midnight
    car: Paper Boats
2. The phone shuffles, then plays the playlist in order:
    phone: Last Bus Home
    phone: Paper Boats
    phone: Monsoon Drive
    phone: Highway 48
    phone: Chai at Midnight
    phone: Last Bus Home
    phone: Paper Boats
    phone: Monsoon Drive
    phone: Highway 48
    phone: Chai at Midnight
3. A caller removes Tara Sen while looping by index:
    phone: Last Bus Home
    phone: Paper Boats
    phone: Highway 48
    phone: Chai at Midnight
4. Repeat-all on an empty playlist:
    crashed: java.lang.ArithmeticException: / by zero

The car played "Monsoon Drive" twice and never played "Highway 48". The phone played a fair shuffle, but Collections.shuffle reordered the real list, so the playlist's own order is gone for every other caller. The index loop in step 3 removed "Monsoon Drive", every song moved up one place, and the loop skipped "Highway 48", so a Tara Sen song survived. Repeat-all on an empty list divided by zero.

This version is fine for one caller that only plays in order. The trouble starts with more modes and more callers.

Every caller owns the walking logic. The phone and the car each have a shuffle and a repeat-all. They behave differently, and a fix in one never reaches the other.

Any caller can change the list. The getter returns the real list, so Collections.shuffle or a remove in one caller changes what every other caller sees.

An index loop cannot see changes. A loop that keeps i while the list shrinks under it skips a song or runs off the end, and nothing reports it.

Where the walking logic lives
On the left, the playlist hands its list to the phone app and the car stereo. Each caller keeps its own index and its own shuffle, and the phone's shuffle reorders the shared list, shown in red. On the right, the callers ask the playlist for a walk and only call hasNext and next. The playlist and its iterator classes are the only code that touches the list.On the left, the playlist hands its list to the phone app and the car stereo. Each caller keeps its own index and its own shuffle, and the phone's shuffle reorders the shared list, shown in red. On the right, the callers ask the playlist for a walk and only call hasNext and next. The playlist and its iterator classes are the only code that touches the list.
In the first version every caller reaches into the list. With iterators, callers only ask for the next song. On the left, the playlist hands its list to the phone app and the car stereo. Each caller keeps its own index and its own shuffle, and the phone's shuffle reorders the shared list, shown in red. On the right, the callers ask the playlist for a walk and only call hasNext and next. The playlist and its iterator classes are the only code that touches the list.

The idea

The pattern works like this:

  • The collection keeps its storage private. It never hands out its list or its indexes.
  • Each way of walking becomes a class. An object of that class holds one walk's place, and nothing else.
  • A caller asks the collection for a walk, then calls two methods on it: "is there another one?" and "give me the next one".
  • Each call for a walk creates a new walk object, so two walks never share a place.

The pattern has two names for its parts. The object that walks is the iterator. The thing being walked, our Playlist, is the aggregate, or simply the collection.

Building it, step by step

Step 1: use Java's own two interfaces

Java already has the two interfaces this pattern needs. java.util.Iterator is the walk: hasNext() and next(). java.lang.Iterable is anything that can start a walk: one method, iterator(). Any Iterable works in a for-each loop.

music/Playlist.javalines 11–23 of 86
public class Playlist implements Iterable<Song> {    private final List<Song> songs = new ArrayList<>();    private final RandomGenerator random;    private int changeCount;     public Playlist(RandomGenerator random) {        this.random = Objects.requireNonNull(random, "random");    }     public void add(Song song) {        songs.add(Objects.requireNonNull(song, "song"));        changeCount++;    }
music/Playlist.javalines 55–58 of 86
    }     @Override    public Iterator<Song> iterator() {

Playlist implements Iterable of Song, so for (Song song : playlist) walks it in order. The list itself is private, and no method returns it.

Decision

Do we use Java's Iterator, or our own interface?

Our own interface, such as SongCursor with hasMore() and nextSong()

This gives us names we like and no rules we did not choose. But a for-each loop only works on Iterable, so every caller writes a while loop by hand. Java's forEach and streams do not work on it either.

java.util.Iterator and IterableOur pick

For-each loops and forEach work directly, streams need one StreamSupport call, and any Java developer already knows the methods. The cost is that we must keep Java's contract: next() throws NoSuchElementException when nothing is left, and remove() either works or throws UnsupportedOperationException.

Step 2: the in-order walk

The in-order iterator holds three things: the playlist, the index of the next song, and a number we come back to in Step 3.

music/InOrderIterator.javalines 6–31 of 31
final class InOrderIterator implements Iterator<Song> {    private final Playlist playlist;    private final int expectedChangeCount;    private int nextIndex;     InOrderIterator(Playlist playlist) {        this.playlist = playlist;        this.expectedChangeCount = playlist.changeCount();    }     @Override    public boolean hasNext() {        playlist.checkUnchanged(expectedChangeCount);        return nextIndex < playlist.size();    }     @Override    public Song next() {        if (!hasNext()) {            throw new NoSuchElementException("No songs left in this walk");        }        Song song = playlist.songAt(nextIndex);        nextIndex++;        return song;    }}

The place in the walk lives in the iterator's nextIndex field, not in the playlist. That is what lets the phone and the car walk the same playlist at once.

next() calls hasNext() first. When nothing is left, it throws NoSuchElementException, as Java's contract asks. It never returns null, because null would reach a caller as a song and fail somewhere far from the cause.

The class is final and package-private. Code outside the music package cannot create one directly. It can only ask a playlist for one.

Step 3: noticing a change in the middle of a walk

Suppose the user adds a song while the in-order walk is on its third song. The walk's index still points at the right place, so nothing breaks. Now suppose the user removes the first song. Every song moves up one place, and the next next() skips one. This is the bug the first version showed in step 3.

The playlist counts its changes. Every add adds one to changeCount, and so does every removeIf that removes something:

music/Playlist.javalines 20–23 of 86
    public void add(Song song) {        songs.add(Objects.requireNonNull(song, "song"));        changeCount++;    }

A walk reads the count when it starts and keeps it in expectedChangeCount. Every hasNext() asks the playlist to compare:

music/Playlist.javalines 69–83 of 86
    }     // Package-private: only the iterators in this package read the list.     Song songAt(int index) {        return songs.get(index);    }     int changeCount() {        return changeCount;    }     void checkUnchanged(int expectedChangeCount) {        if (changeCount != expectedChangeCount) {            throw new ConcurrentModificationException("The playlist changed during this walk");

If the counts differ, the walk throws ConcurrentModificationException at the next step, and the caller learns about the change at once.

Decision

What happens when the playlist changes during a walk?

Nothing: the walk reads the list as it is now

This is the first version's behaviour. A walk silently skips a song, plays one twice, or runs off the end with an IndexOutOfBoundsException, depending on where the change happened.

Each walk takes a copy of the list when it starts

A change never disturbs a walk that is already going on, and a walk never fails. The cost is one copy of the list per walk, and a removed song still plays in a walk that started before it was removed.

Copy the list on every change, and let each walk read the copy it started with

Walks then cost nothing and never fail. This is what a CopyOnWriteArrayList does, and the Observer pattern page chooses it for its listener list, because there changes are rare and walks happen on every event. A playlist being edited changes on every add, and each add would copy the whole list.

Fail fast: the walk throws at its next stepOur pick

A walk costs no copy, and a mistake shows up at the line that caused it. Here the loop belongs to the caller, so an edit inside it changes the very thing the caller is walking. A caller that needs to remove songs uses removeIf, below. A player that must let the user edit the playlist while it plays walks playlist.snapshot() instead, which is the second option, chosen on purpose for that one caller.

The check runs in hasNext(), not only in next(). Java's own ArrayList checks only in next(). Its hasNext() just compares the place with the size. If a for-each loop removes the second-to-last item, the size drops to the place, hasNext() returns false, and the loop ends quietly without the last item and without an exception. Our hasNext() checks first, so the same mistake throws.

Removing the second-to-last song during a for-each
The walk has just played Paper Boats, the fourth of five songs, and the caller removes it. The walk's place is now 4 and the size is 4. On the left, hasNext() only compares the place with the size, returns false, and the loop ends without playing Last Bus Home, shown in red. On the right, hasNext() first compares the change count, which went from 5 to 6, and throws.The walk has just played Paper Boats, the fourth of five songs, and the caller removes it. The walk's place is now 4 and the size is 4. On the left, hasNext() only compares the place with the size, returns false, and the loop ends without playing Last Bus Home, shown in red. On the right, hasNext() first compares the change count, which went from 5 to 6, and throws.
A check only in next() lets the loop end quietly. A check in hasNext() catches it. The walk has just played Paper Boats, the fourth of five songs, and the caller removes it. The walk's place is now 4 and the size is 4. On the left, hasNext() only compares the place with the size, returns false, and the loop ends without playing Last Bus Home, shown in red. On the right, hasNext() first compares the change count, which went from 5 to 6, and throws.

Five more points apply to the check:

  • An add stops the walk too. An in-order walk could survive a song added at the end, but the shuffle built its index array when it started and would never play the new song. One rule for every change is easier to trust than one rule per mode.
  • The change itself goes through. The exception stops the walk, not the edit. In the demo below, "Toll Plaza" is added during a walk, the walk stops, and the song stays in the playlist.
  • A speaker can trigger it too. The Speaker that the player calls is outside code. If a speaker adds a song to the playlist inside play, the walk throws at its next step, the same way.
  • The check is not a lock. Playlist is not thread-safe, like ArrayList, and the count only catches mistakes within one thread.
  • These are programmer errors. The exception points at a bug in the calling code. Application code should not catch it and carry on; the demo catches it only to print it.

A player that lets the user edit the playlist while it plays walks a snapshot, a second playlist with the same songs:

music/Playlist.javalines 49–53 of 86
    }     public Playlist snapshot() {        Playlist copy = new Playlist(random);        copy.songs.addAll(songs);

The snapshot has its own list and its own change count, so edits to the playlist never reach a walk over the snapshot. It shares the random source, so one seeded generator still decides every shuffle.

Decision

Can a caller remove a song through the iterator?

Yes: remove() takes out the song the walk just returned

ArrayList's iterator works this way. For a shuffle, though, removing a song shifts every later index, and the array of unplayed indexes must be fixed up. Each iterator would need its own removal logic.

No: iterators are read-only, and the playlist has removeIfOur pick

Our iterators keep Java's default remove(), which throws UnsupportedOperationException. A caller that wants to remove songs while looking at them calls playlist.removeIf(song -> song.artist().equals("The Ghats")). The playlist removes every match in one call, and counts it as one change.

music/Playlist.javalines 25–45 of 86
    public boolean removeIf(Predicate<Song> filter) {        Objects.requireNonNull(filter, "filter");        int changesBefore = changeCount;        // Decide on a copy first, so a filter that throws or changes the playlist removes nothing.        List<Song> kept = new ArrayList<>();        for (Song song : List.copyOf(songs)) {            if (!filter.test(song)) {                kept.add(song);            }        }        if (changeCount != changesBefore) {            throw new ConcurrentModificationException("The filter changed the playlist");        }        if (kept.size() == songs.size()) {            return false;        }        songs.clear();        songs.addAll(kept);        changeCount++;        return true;    }

removeIf runs the filter over a copy of the list and builds the list of songs to keep. Only after every song has been tested does it touch the playlist. If the filter throws, nothing is removed and the exception reaches the caller unchanged. If the filter itself changes the playlist, by adding a song or by calling removeIf again, lines 35 to 37 throw a ConcurrentModificationException saying so. The filter's own change stays, and the outer call removes nothing. The filter always sees the original songs, never a removed slot or a null. The rule for callers is still simple: never change the playlist from inside the filter.

Step 4: a fair shuffle

The shuffle iterator must play every song exactly once, in an order where every order is equally likely. The car stereo's random index per song fails the first rule. The phone's Collections.shuffle passes both rules but reorders the playlist.

The shuffle iterator keeps its own array of song indexes, order, starting as 0, 1, 2 and so on. Each call to next() picks one of the songs not played yet:

music/ShuffleIterator.javalines 30–42 of 43
    @Override    public Song next() {        if (!hasNext()) {            throw new NoSuchElementException("Every song in this shuffle has played");        }        // Pick any song not played yet, then swap it into the played part of the array.        int pick = played + random.nextInt(order.length - played);        int chosen = order[pick];        order[pick] = order[played];        order[played] = chosen;        played++;        return playlist.songAt(chosen);    }

Everything before position played in the array has been played, and everything from played on has not. Line 36 picks a random position among the unplayed ones. Lines 37 to 39 swap that song into position played, and line 40 grows the played part by one.

This is the Fisher-Yates shuffle, done one step at a time. At each step every unplayed song has the same chance, one in the number left, so every order of the whole playlist is equally likely. One easy slip is random.nextInt(order.length), which can pick a song already played. Another is a range one short, which never picks the last unplayed song. Both look right and play biased orders.

The playlist is never touched. The array holds indexes, and the change count keeps them correct while the walk lasts.

Decision

Where does the randomness come from?

new Random() inside the shuffle iterator

This is the simplest. But no test can know what order to expect, and the iterator creates its own collaborator, so nothing outside can replace it.

A RandomGenerator passed into the playlistOur pick

Playlist takes a java.util.random.RandomGenerator in its constructor and hands it to each shuffle. The app passes a normal Random. A test passes new Random(7) and knows the order of the first shuffle. Later shuffles draw further numbers from the same generator, so each one gets a different order. The demo below uses seed 7, which shuffles the five songs to "Chai at Midnight", "Paper Boats", "Highway 48", "Monsoon Drive" and "Last Bus Home".

Step 5: a walk that never ends

Repeat-all wraps around to the first song after the last:

music/RepeatAllIterator.javalines 16–30 of 31
    @Override    public boolean hasNext() {        playlist.checkUnchanged(expectedChangeCount);        return playlist.size() > 0;    }     @Override    public Song next() {        if (!hasNext()) {            throw new NoSuchElementException("The playlist is empty");        }        Song song = playlist.songAt(nextIndex);        nextIndex = (nextIndex + 1) % playlist.size();        return song;    }

hasNext() returns true for as long as the playlist has songs. A for-each loop over repeat-all therefore never ends, and the code says so where the mode is declared:

music/PlayMode.javalines 3–8 of 8
public enum PlayMode {    IN_ORDER,    SHUFFLE,    // Never ends on its own while the playlist has songs: the caller decides when to stop.    REPEAT_ALL}

On an empty playlist, hasNext() returns false at once, so the first version's divide by zero cannot happen.

Decision

Does repeat-all ever stop on its own?

Yes, after a fixed number of rounds

Callers could then loop over it safely with for-each. But the playlist would have to guess the number, and the guess belongs to the listener or the player.

No: the walk is endless, and the caller sets the limitOur pick

The walk does one job: give the next song. The player decides how many to play. The cost is that any caller of repeat-all must bound its loop, so the enum states it in a comment.

The player bounds every walk the same way:

player/Player.javalines 15–28 of 29
    public int play(Iterable<Song> walk, int maxSongs) {        Objects.requireNonNull(walk, "walk");        if (maxSongs < 0) {            throw new IllegalArgumentException("maxSongs cannot be negative, got " + maxSongs);        }        int played = 0;        Iterator<Song> songs = walk.iterator();        // Check the limit first, so an endless walk is never asked for one song too many.        while (played < maxSongs && songs.hasNext()) {            speaker.play(songs.next());            played++;        }        return played;    }

The loop compares played with maxSongs before it calls hasNext(). A for-each loop that checks the limit at the top of its body asks an endless walk for one song more than it plays, then throws that song away.

Step 6: one loop for every mode

The last piece turns a mode into a walk:

music/Playlist.javalines 60–67 of 86
    }     public Iterable<Song> play(PlayMode mode) {        Objects.requireNonNull(mode, "mode");        return switch (mode) {            case IN_ORDER -> () -> new InOrderIterator(this);            case SHUFFLE -> () -> new ShuffleIterator(this, random);            case REPEAT_ALL -> () -> new RepeatAllIterator(this);

play(mode) returns an Iterable, written as a lambda. Each time a caller starts a loop, the lambda creates a new iterator, so a second loop over the same Iterable starts from the beginning with its own place.

Java's Iterable also gives us internal iteration. With external iteration, the caller drives the loop with hasNext() and next(). With internal iteration, the caller passes a function and the collection drives:

Sketchnot part of the final code
playlist.forEach(song -> System.out.println(song.title())); StreamSupport.stream(playlist.play(PlayMode.REPEAT_ALL).spliterator(), false)        .limit(8)        .forEach(speaker::play);

The stream needs limit(8), for the same reason the player needs maxSongs. Without it, the stream over repeat-all never ends.

The finished design

The finished design
Playlist implements Java's Iterable and holds its list of songs, its change count and its RandomGenerator. It creates the three iterator classes, which all implement Java's Iterator and read the list through package-private methods. PlayMode is the enum a caller passes to play. Player is given an Iterable, walks the Iterator it returns, and sends each song to a Speaker.Playlist implements Java's Iterable and holds its list of songs, its change count and its RandomGenerator. It creates the three iterator classes, which all implement Java's Iterator and read the list through package-private methods. PlayMode is the enum a caller passes to play. Player is given an Iterable, walks the Iterator it returns, and sends each song to a Speaker.
The playlist hands out walks. Each walk is an iterator with its own place. Playlist implements Java's Iterable and holds its list of songs, its change count and its RandomGenerator. It creates the three iterator classes, which all implement Java's Iterator and read the list through package-private methods. PlayMode is the enum a caller passes to play. Player is given an Iterable, walks the Iterator it returns, and sends each song to a Speaker.

Here is one step of a shuffle, traced through the objects:

One step of a shuffle
The player calls hasNext on the shuffle iterator (1), which asks the playlist to compare change counts (2). The player then calls next (3). The iterator asks the RandomGenerator for a position among the unplayed songs (4), swaps it into the played part of its own array, and reads that song from the playlist with songAt (5). The player hands the song to the speaker (6).The player calls hasNext on the shuffle iterator (1), which asks the playlist to compare change counts (2). The player then calls next (3). The iterator asks the RandomGenerator for a position among the unplayed songs (4), swaps it into the played part of its own array, and reads that song from the playlist with songAt (5). The player hands the song to the speaker (6).
The player only calls hasNext and next. The iterator does the checking and the picking. The player calls hasNext on the shuffle iterator (1), which asks the playlist to compare change counts (2). The player then calls next (3). The iterator asks the RandomGenerator for a position among the unplayed songs (4), swaps it into the played part of its own array, and reads that song from the playlist with songAt (5). The player hands the song to the speaker (6).

The whole project is below. Click any class name in the code to open that class.

musicPlaylist.java
package music; import java.util.ArrayList;import java.util.ConcurrentModificationException;import java.util.Iterator;import java.util.List;import java.util.Objects;import java.util.function.Predicate;import java.util.random.RandomGenerator; public class Playlist implements Iterable<Song> {    private final List<Song> songs = new ArrayList<>();    private final RandomGenerator random;    private int changeCount;     public Playlist(RandomGenerator random) {        this.random = Objects.requireNonNull(random, "random");    }     public void add(Song song) {        songs.add(Objects.requireNonNull(song, "song"));        changeCount++;    }     public boolean removeIf(Predicate<Song> filter) {        Objects.requireNonNull(filter, "filter");        int changesBefore = changeCount;        // Decide on a copy first, so a filter that throws or changes the playlist removes nothing.        List<Song> kept = new ArrayList<>();        for (Song song : List.copyOf(songs)) {            if (!filter.test(song)) {                kept.add(song);            }        }        if (changeCount != changesBefore) {            throw new ConcurrentModificationException("The filter changed the playlist");        }        if (kept.size() == songs.size()) {            return false;        }        songs.clear();        songs.addAll(kept);        changeCount++;        return true;    }     public int size() {        return songs.size();    }     public Playlist snapshot() {        Playlist copy = new Playlist(random);        copy.songs.addAll(songs);        return copy;    }     @Override    public Iterator<Song> iterator() {        return new InOrderIterator(this);    }     public Iterable<Song> play(PlayMode mode) {        Objects.requireNonNull(mode, "mode");        return switch (mode) {            case IN_ORDER -> () -> new InOrderIterator(this);            case SHUFFLE -> () -> new ShuffleIterator(this, random);            case REPEAT_ALL -> () -> new RepeatAllIterator(this);        };    }     // Package-private: only the iterators in this package read the list.     Song songAt(int index) {        return songs.get(index);    }     int changeCount() {        return changeCount;    }     void checkUnchanged(int expectedChangeCount) {        if (changeCount != expectedChangeCount) {            throw new ConcurrentModificationException("The playlist changed during this walk");        }    }}
Click a class name in the code to open its fileJava · 86 lines · 337 in the project

The demo in demo/Main.java builds the five-song playlist with seed 7 and runs through every mode:

$ java demo.Main
1. For-each over the playlist itself:
    Monsoon Drive
    Chai at Midnight
    Highway 48
    Paper Boats
    Last Bus Home
2. The same player, every mode, at most 7 songs:
  IN_ORDER:
    Monsoon Drive - Tara Sen (3:34)
    Chai at Midnight - The Ghats (3:07)
    Highway 48 - Tara Sen (4:03)
    Paper Boats - Neel and Ira (3:19)
    Last Bus Home - The Ghats (3:46)
  played 5
  SHUFFLE:
    Chai at Midnight - The Ghats (3:07)
    Paper Boats - Neel and Ira (3:19)
    Highway 48 - Tara Sen (4:03)
    Monsoon Drive - Tara Sen (3:34)
    Last Bus Home - The Ghats (3:46)
  played 5
  REPEAT_ALL:
    Monsoon Drive - Tara Sen (3:34)
    Chai at Midnight - The Ghats (3:07)
    Highway 48 - Tara Sen (4:03)
    Paper Boats - Neel and Ira (3:19)
    Last Bus Home - The Ghats (3:46)
    Monsoon Drive - Tara Sen (3:34)
    Chai at Midnight - The Ghats (3:07)
  played 7
3. The playlist order after shuffling:
    Monsoon Drive
    Chai at Midnight
    Highway 48
    Paper Boats
    Last Bus Home
4. Adding a song in the middle of a walk:
    Monsoon Drive
    Chai at Midnight
    Highway 48
    stopped: The playlist changed during this walk
5. Walking a snapshot while songs are added to the playlist:
    Monsoon Drive
    Chai at Midnight
    Highway 48
    Paper Boats
    Last Bus Home
    Toll Plaza
  the walk finished; the playlist now has 7 songs
6. Removing every song by The Ghats, safely:
    Monsoon Drive
    Highway 48
    Paper Boats
    Toll Plaza
    Rain Check
7. Repeat-all on an empty playlist:
  played 0

Step 1 walks the playlist with for-each. Step 2 passes all three modes to the same player.play(…, 7). In order and shuffle stop after 5. Repeat-all plays 7, with "Monsoon Drive" and "Chai at Midnight" played again as songs 6 and 7. Step 3 shows the playlist's own order, unchanged by the shuffle. In step 4 the walk stops right after "Highway 48", where the song was added, but "Toll Plaza" stays in the playlist. Step 5 walks a snapshot while "Rain Check" is added to the playlist: the walk finishes all six songs it started with, and the playlist now has 7. Step 6 shows both added songs still there after removeIf takes out The Ghats. Step 7 runs repeat-all on an empty playlist and plays 0 songs.

What it costs

The pattern makes one kind of change cheap and another a little more work.

A new way of walking is cheap. A "reverse order" mode is one new iterator class, one enum value and one line in play. No caller changes.

A change to the storage touches every iterator. If the playlist moved from a list to pages loaded from a server, all three iterator classes would change. Each one reads through songAt(index) and size(), and paged storage has neither cheaply: with 100 songs a page, reaching song 900 means loading its page first, and the total may not be known until the last page arrives. Callers would still not change.

Which change is cheap
On the left, adding a reverse-order mode adds one iterator class, tagged new, and edits PlayMode and Playlist, tagged edited with amber outlines. On the right, changing how songs are stored edits Playlist and all three iterators, tagged the same way. Unchanged boxes have grey outlines. In both cases the callers, the phone app, the car stereo and the player, do not change.On the left, adding a reverse-order mode adds one iterator class, tagged new, and edits PlayMode and Playlist, tagged edited with amber outlines. On the right, changing how songs are stored edits Playlist and all three iterators, tagged the same way. Unchanged boxes have grey outlines. In both cases the callers, the phone app, the car stereo and the player, do not change.
A new walk is one new class. New storage touches every iterator, but never a caller. On the left, adding a reverse-order mode adds one iterator class, tagged new, and edits PlayMode and Playlist, tagged edited with amber outlines. On the right, changing how songs are stored edits Playlist and all three iterators, tagged the same way. Unchanged boxes have grey outlines. In both cases the callers, the phone app, the car stereo and the player, do not change.

There are smaller costs too. Each walk is a small object, each shuffle allocates an array the size of the playlist, and the fail-fast rule asks callers to use removeIf or a snapshot instead of editing inside their own loops.

When an iterator is too much

If callers only ever read the songs in order, and the list is small, an unmodifiable copy does the job:

Sketchnot part of the final code
public List<Song> songs() {    return List.copyOf(songs);}

Callers can loop over the copy or stream it, and sort a further copy of it. The copy is unmodifiable, so sort on it throws. No copy can change the playlist. Each call copies the whole list, and a copy cannot represent an endless walk or songs arriving a page at a time.

Iterator or a copy of the list?

These two are the real choice when a collection is shared:

IteratorA copy of the list
Memory per walkA place, plus an index array for shuffleThe whole list
Sees later changesNo: fails fast at the next stepNo: keeps the old songs
Endless walksYes, with a limit set by the callerNo
Items that arrive lazily, such as pages from a serverYes, one at a timeNo, everything up front
Random accessNoYes, with get(index)
SortingNoOn a further copy

A short way to say it: an iterator hands out one item at a time and keeps the collection's shape hidden; a copy hands out everything at once.

The Composite pattern page meets the same question for a folder tree. It skips an iterator because the depth limit keeps the recursion safe and every question already lives on the nodes. It also names the case where an iterator would fit: a caller that needs to stop early, such as "find the first file over 1 GB". The Visitor pattern answers a different question. An iterator decides the order of a walk. A visitor decides what to do with each kind of item.

In an interview

The Iterator pattern appears in two kinds of question. The first is a design question with a collection inside it, such as a music player or a paginated search. The second asks for an iterator directly: over a binary search tree in sorted order, over a nested list, or one that can peek at the next item.

We suggest presenting it in this order:

  1. Separate the collection from the walks. Draw one collection and several walks, as in the first figure.
  2. Write one iterator in full, with hasNext(), next() and the NoSuchElementException.
  3. Say what happens when the collection changes during a walk, and why you chose it.
  4. Mention endless or lazy walks, if the question has them, and who sets the limit.

Two follow-ups test the design. If the listener switches from in order to shuffle halfway through, a fresh shuffle replays songs already heard. The player can shuffle a snapshot instead, with one copy of each played song removed. A "previous" button needs a walk that can go back. Java's ListIterator has previous() for an in-order walk, and a shuffle can keep a stack of the songs it has played.

Avoid these mistakes:

  • A getter that returns the internal list. Every caller can then reorder or edit it, as the phone's shuffle did.
  • One cursor field on the collection. Two walks then share one place and jump over each other's songs.
  • next() that returns null at the end. The null travels until something calls a method on it.
  • A shuffle that picks a random index each time, which repeats songs, or that shuffles the shared list, which changes the order for everyone.
  • An endless iterator that does not say so. Any for-each loop over it hangs.
  • Removing items inside a for-each loop. Use removeIf, or collect what to remove and remove it after the loop.

Summary

  • Use the Iterator pattern when callers need to walk a collection in more than one way, without seeing how it stores its items.
  • The collection keeps its storage private and hands out a new iterator for each walk. The walk's place lives in the iterator.
  • Implement Java's Iterator and Iterable, so for-each and forEach work directly and streams take one StreamSupport call. Keep their contract: NoSuchElementException at the end.
  • Decide what a change during a walk does. We fail fast, and check in hasNext() as well as next().
  • A fair shuffle picks among the unplayed items at each step, with a random source passed in.
  • An endless walk must say so, and the caller sets the limit.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.