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.
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())?
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.
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.
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.
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);
}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.
(ArrayWalk and ChainWalk stand for the two anonymous classes above.)
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 is | something you can walk | one walk in progress |
| Main method | iterator() | hasNext(), next() |
| How many | one collection | as many as there are walks |
| Keeps a place? | no | yes |
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.
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.
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);
}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.
List and get by index.List.copyOf(songs)). Don’t write an iterator by hand.Reach for an iterator when callers outside the class shouldn’t know its shape, and that shape might change.
hasNext and next, that keeps its own place.Iterable, and for-each works. Change the storage, and the loops never notice.removeIf; fail-fast exceptions are for finding bugs.forEach and streams are internal iteration.Checklist:
Walk it. Don’t open it.
Related lessons:
Factory Method (iterator() creates the
iterator),
Abstract Factory,
Encapsulation,
Polymorphism.
Iterator,
ArrayList (fail-fast iterators),
java.util.stream.