BackendBench
Coffee
Spot the Bug #24

The sublist that stopped working

A hard Java puzzle in the modifying while iterating family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

hardModifying while iteratingbuggy line: 7

Highlighted: line 7. Play this one as a puzzle without the answer.

What is wrong

subList returns a live view of the original list, not a copy. Structurally modifying the parent afterwards invalidates the view, and reading it throws ConcurrentModificationException.

The fix

List<Integer> firstThree = new ArrayList<>(all.subList(0, 3));

How to avoid it next time

Copy a sublist if it must outlive changes to the source. Treat views as temporary.

Want the background? Read Collections: List, Set, Map in the Java concepts library.

About modifying while iterating

Collections detect structural changes made during iteration and throw ConcurrentModificationException, but only some of the time, and not at all for certain patterns. Removing in a loop is a classic way to skip elements or crash.

In code review: Any call to add or remove on the collection being looped over deserves suspicion. Use Iterator.remove, removeIf, or build a new collection.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #23#25 โ†’

Frequently asked questions

What is the bug in "The sublist that stopped working"?

subList returns a live view of the original list, not a copy. Structurally modifying the parent afterwards invalidates the view, and reading it throws ConcurrentModificationException. The faulty line is line 7: all.add(6);

How do I fix it?

Replace it with: List firstThree = new ArrayList<>(all.subList(0, 3));. Copy a sublist if it must outlive changes to the source. Treat views as temporary.

How do I catch modifying while iterating in code review?

Any call to add or remove on the collection being looped over deserves suspicion. Use Iterator.remove, removeIf, or build a new collection.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need