Iterator

November 26, 20269 minutes

A playlist changes how it stores songs and twelve loops break. Learn how an iterator hides a collection's insides, how to remove safely while looping, how to page an API, and when streams fit better.

The playlist class in a music app changed how it stores songs. And twelve loops across the app stopped compiling. The songs used to sit in an array. Now they’re a chain of nodes, so moving a song is cheap. Every loop broke, and none of them cared how songs were stored. They only wanted the next one. So why does every loop know how songs are stored? The Iterator pattern is the answer, and you use it every day.

Prefer to watch? The narrated video covers the same lesson (about 8 minutes). The article follows it section by section, with diagrams and a little extra depth.

Twelve loops that only wanted the next song

Twelve parts of the music app (player, shuffle, export, search and others) each loop over the playlist's array directly. When the playlist switches to a chain of nodes, every one of them breaks. Twelve parts of the music app (player, shuffle, export, search and others) each loop over the playlist's array directly. When the playlist switches to a chain of nodes, every one of them breaks.
Callers that reach into a collection break when its insides change.

The audio guide

Think of a museum audio guide. You press next, and you hear about the next exhibit. You never need the floor plan. The museum can move its rooms around, and the guide still walks you through. You press next, exactly as before. And every visitor has their own guide, each at its own place in the museum. And if staff move a painting while you’re mid-route, a careful guide stops, and tells you the route is out of date. Remember that one.

In the pattern’s words, the museum is the collection (GoF: the aggregate), and the guide is the iterator. It asks two questions: is there more (hasNext())? And: what’s next (next())?

The audio guide mapped onto code: the museum is the collection (Playlist); the guide is the iterator; the question 'is there more?' is hasNext(); pressing next is next(). The audio guide mapped onto code: the museum is the collection (Playlist); the guide is the iterator; the question 'is there more?' is hasNext(); pressing next is next().
The guide knows the route; you only press next.

The obvious version: hand out the array

Here’s where the music app started. The playlist keeps its songs in an array, with a count, and hands the array out with a getter.

public class Playlist {
    private Song[] songs = new Song[100];
    private int count;

    public Song[] getSongs() { return songs; }
    public int size() { return count; }
}

Callers take the array and loop with an index, up to the size.

Song[] songs = playlist.getSongs();
for (int i = 0; i < playlist.size(); i++) {
    play(songs[i]);
}

And that’s fair. It’s direct, it’s fast, and every Java developer reads it at a glance. Plenty of small apps keep this for years.

Why it breaks

But look at what every caller now knows. The songs are in an array. It’s indexed. And only the first count slots are real. Change any of those, a chain of nodes, or songs loaded page by page, and every loop has to change with it.

And since callers hold the real array, any one of them can write songs[3] = null; and break the playlist for everyone. It’s handing every visitor the floor plan. Move one room, and you reprint every plan.

What every caller of getSongs knows: it's an array, it's indexed, only count slots are real, and it holds the real array so it can write into it. Each of these couples the caller to the playlist's insides. What every caller of getSongs knows: it's an array, it's indexed, only count slots are real, and it holds the real array so it can write into it. Each of these couples the caller to the playlist's insides.
The insides leaked.

The key idea: give the walk its own object

So don’t hand out the array. Hand out a small object that walks it for you: an iterator. It answers two questions. Has next: is there more? And next: give me the next one, and move along.

public interface Iterator<T> {
    boolean hasNext();
    T next();
}

(That’s the heart of java.util.Iterator, simplified: the real interface also has default methods, remove and forEachRemaining.) The collection makes a fresh iterator for every walk, and each one keeps its own place. The Gang of Four state the intent like this: “Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.”

Walk it. Don’t open it. The iterator keeps your place.

Building it in Java: Iterable, the iterator, for-each

In Java, the playlist implements Iterable. That’s one method, iterator(), which returns a new iterator over the array. The iterator keeps an index. hasNext checks it against the count. next returns the song and moves on, and throws if nothing is left.

public class Playlist implements Iterable<Song> {
    private Song[] songs = new Song[100];
    private int count;

    public Iterator<Song> iterator() {
        return new Iterator<>() {
            private int i = 0;
            public boolean hasNext() { return i < count; }
            public Song next() {
                if (!hasNext()) throw new NoSuchElementException();
                return songs[i++];
            }
        };
    }
}

Now the for-each loop works on a playlist. The compiler turns it into calls to iterator, hasNext, and next (Java Language Specification, §14.14.2).

for (Song s : playlist) {
    play(s);
}
Sequence: the for-each loop calls iterator() on the Playlist once and gets an Iterator; then it repeatedly calls hasNext() and next() on the Iterator until hasNext() returns false. Sequence: the for-each loop calls iterator() on the Playlist once and gets an Iterator; then it repeatedly calls hasNext() and next() on the Iterator until hasNext() returns false.
What the compiler turns for-each into.

Then switch the playlist to a chain of nodes. Only the iterator method changes: it follows the links instead of counting.

public Iterator<Song> iterator() {
    return new Iterator<>() {
        private Node node = first;
        public boolean hasNext() { return node != null; }
        public Song next() {
            if (node == null) throw new NoSuchElementException();
            Song s = node.song;
            node = node.next;
            return s;
        }
    };
}

And every for-each loop stays exactly as it was. Who creates the iterator is a factory method, by the way (see Factory Method, which uses Iterable.iterator() as its example), but here we care about the iterator itself.

Class diagram: Playlist implements Iterable of Song and creates an Iterator of Song; the loop depends only on Iterable and Iterator; the array iterator and the chain iterator both implement Iterator. Class diagram: Playlist implements Iterable of Song and creates an Iterator of Song; the loop depends only on Iterable and Iterator; the array iterator and the chain iterator both implement Iterator.
Callers see Iterable and Iterator; the storage hides behind them.

(ArrayWalk and ChainWalk stand for the two anonymous classes above.)

Several walks at once

Because each call makes a new iterator, two walks can run at the same time. The player is on song three, while the export is on song seven. The Gang of Four list this as a benefit: “More than one traversal can be pending on an aggregate.”

That’s also the line between Iterable and Iterator. An iterable is something you can walk, again and again. An iterator is one walk in progress.

Iterable<T>Iterator<T>
What it issomething you can walkone walk in progress
Main methoditerator()hasNext(), next()
How manyone collectionas many as there are walks
Keeps a place?noyes

Removing while you walk

A common belief is that removing from a list inside a for-each loop is fine, if you’re careful. Here’s the loop that removes skipped songs.

for (Song s : songs) {                    // songs: an ArrayList<Song>
    if (s.isSkipped()) songs.remove(s);   // the list changes behind the iterator
}

The list changes, but the loop’s iterator doesn’t know. ArrayList’s iterator notices on its next step, and throws a ConcurrentModificationException. That’s called fail-fast. Like the careful guide, it stops, instead of skipping a song or playing one twice (the Gang of Four’s warning: “you might end up accessing an element twice or missing it completely”). But it’s best effort: the ArrayList docs say “the fail-fast behavior of iterators should be used only to detect bugs.”

Remove the second-to-last song, and there’s no exception at all. The loop simply ends, and the last song is never checked.

Sequence: the loop's iterator is at song two; the loop calls songs.remove on the list directly; the list changes; on the next step the iterator detects the change and throws ConcurrentModificationException. If the removed song was second to last, hasNext returns false instead and the last song is skipped. Sequence: the loop's iterator is at song two; the loop calls songs.remove on the list directly; the list changes; on the next step the iterator detects the change and throws ConcurrentModificationException. If the removed song was second to last, hasNext returns false instead and the last song is skipped.
The list changed behind the iterator's back.

The fix is to remove through the iterator. Its remove method deletes the song that next just returned (it may be called once per call to next).

Iterator<Song> it = songs.iterator();
while (it.hasNext()) {
    if (it.next().isSkipped()) it.remove();
}

Or let the list do the whole job, with removeIf:

songs.removeIf(Song::isSkipped);

remove is an optional operation: the interface’s default throws UnsupportedOperationException, so an iterator over a read-only source simply doesn’t support it.

Your own iterator: a paged API

Writing your own iterator pays off when items come from somewhere awkward. Say an orders API returns thirty orders a page. Callers want every order, and they don’t care about pages. So a small iterator does the paging for them. When its current page runs out, hasNext fetches the next one. It stops at the first empty page.

public class PagedIterator implements Iterator<Order> {
    private final OrderApi api;
    private List<Order> page = List.of();
    private int pos = 0;
    private int nextPage = 1;
    private boolean done = false;

    public PagedIterator(OrderApi api) { this.api = api; }

    public boolean hasNext() {
        if (pos == page.size() && !done) {
            page = api.fetch(nextPage++);   // one call per page
            pos = 0;
            done = page.isEmpty();
        }
        return pos < page.size();
    }

    public Order next() {
        if (!hasNext()) throw new NoSuchElementException();
        return page.get(pos++);
    }
}

Pages come in only when the loop gets there. A loop that stops early never fetches the rest. Wrap it in an Iterable, and a lambda works here (Iterable has a single abstract method), and a plain for-each loop walks every order.

Iterable<Order> orders = () -> new PagedIterator(api);
for (Order o : orders) {
    ship(o);
}
Sequence: the loop asks the PagedIterator hasNext; when the current page is used up, the iterator calls OrderApi.fetch for the next page; it returns orders from that page one by one; an empty page ends the walk. Sequence: the loop asks the PagedIterator hasNext; when the current page is used up, the iterator calls OrderApi.fetch for the next page; it returns orders from that page one by one; an empty page ends the walk.
The iterator hides the paging.

Internal iteration: forEach and streams

Everything so far was external iteration. Your loop asks for the next item, step by step. With internal iteration, you hand over what to do, and the collection does the walking: forEach with a lambda, or a stream.

playlist.forEach(s -> play(s));

long longSongs = songs.stream()
        .filter(s -> s.seconds() > 300)
        .count();

The Java tutorial puts it this way: with internal iteration “your application determines what collection it iterates, but the JDK determines how to iterate the collection.” That also makes parallel work easier. External iteration is more flexible. You can stop, or walk two collections side by side. The Gang of Four note that comparing two collections is easy with an external iterator, and “practically impossible” with an internal one.

It’s the difference between a guided tour, where the guide walks and you listen, and your own audio guide. And like an iterator, a stream is used only once: the stream docs say a new stream must be made to revisit the same elements, and the source shouldn’t be modified while a pipeline runs.

Comparison: external iteration, where your loop calls hasNext and next and can stop early or walk two collections side by side; internal iteration, where you pass a lambda to forEach or a stream and the library decides how to walk, possibly in parallel. Comparison: external iteration, where your loop calls hasNext and next and can stop early or walk two collections side by side; internal iteration, where you pass a lambda to forEach or a stream and the library decides how to walk, possibly in parallel.
External: you drive. Internal: you say what, the collection drives.

When not to use it

  • You need a position (the fifth song, a binary search): use a List and get by index.
  • Your class already wraps a standard list: return an unmodifiable view, or a copy (List.copyOf(songs)). Don’t write an iterator by hand.
  • You only transform or total the items: a stream says it better.
  • A tiny private array that never leaves the class can keep its plain loop.

Reach for an iterator when callers outside the class shouldn’t know its shape, and that shape might change.

Decision: do callers outside the class walk its items? If not, a plain loop is fine. Do they need positions? Use a List and get. Is it already a standard collection? Return a view or a copy. Are you only transforming or totalling? Use a stream. Otherwise write an iterator. Decision: do callers outside the class walk its items? If not, a plain loop is fine. Do they need positions? Use a List and get. Is it already a standard collection? Return a view or a copy. Are you only transforming or totalling? Use a stream. Otherwise write an iterator.
Iterate when callers outside shouldn't know the shape.

Recap

  • Don’t hand out the insides. Hand out an iterator, with hasNext and next, that keeps its own place.
  • Implement Iterable, and for-each works. Change the storage, and the loops never notice.
  • Remove through the iterator, or with removeIf; fail-fast exceptions are for finding bugs.
  • An iterator can hide paging.
  • forEach and streams are internal iteration.
Recap chain: don't hand out the insides; hand out an iterator; implement Iterable so for-each works; the storage can change and the loops don't notice. Recap chain: don't hand out the insides; hand out an iterator; implement Iterable so for-each works; the storage can change and the loops don't notice.
Walk it. Don't open it.

Checklist:

  • Does any getter hand out an internal array or a mutable list?
  • Can callers walk the items with a for-each loop?
  • Does anything remove from a collection inside a for-each loop?
  • Would a stream say this loop more clearly?
  • If the items come in pages or chunks, does an iterator hide that?

Walk it. Don’t open it.

Related lessons: Factory Method (iterator() creates the iterator), Abstract Factory, Encapsulation, Polymorphism.

Further reading