BackendBench
Coffee
Spot the Bug #19

Removing names inside the loop

A easy 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.

easyModifying while iteratingbuggy line: 7

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

What is wrong

The enhanced for loop uses an iterator that checks the list for structural changes. Removing an element directly from the list makes the next call to next throw ConcurrentModificationException. It would also skip an element if the removal happened to hit the second to last item.

The fix

names.removeIf(String::isEmpty);

How to avoid it next time

Use removeIf, Iterator.remove, or collect the items to keep into a new list.

Want the background? Read ConcurrentModificationException 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โ† #18#20 โ†’

Frequently asked questions

What is the bug in "Removing names inside the loop"?

The enhanced for loop uses an iterator that checks the list for structural changes. Removing an element directly from the list makes the next call to next throw ConcurrentModificationException. It would also skip an element if the removal happened to hit the second to last item. The faulty line is line 7: if (s.isEmpty()) names.remove(s);

How do I fix it?

Replace it with: names.removeIf(String::isEmpty);. Use removeIf, Iterator.remove, or collect the items to keep into a new list.

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