BackendBench
Coffee
Spot the Bug #20

Negative numbers that survive

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

mediumModifying while iteratingbuggy line: 7

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

What is wrong

Removing at index i shifts every later element left, then the loop increments i and skips the element that moved into position i. The two adjacent negatives -1 and -2 leave -2 in the list. There is no exception, only a wrong result.

The fix

data.removeIf(n -> n < 0);

How to avoid it next time

If you must remove by index, iterate backwards or do not increment after a removal. removeIf avoids the problem completely.

Want the background? Read Iterator and Iterable 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← #19#21 →

Frequently asked questions

What is the bug in "Negative numbers that survive"?

Removing at index i shifts every later element left, then the loop increments i and skips the element that moved into position i. The two adjacent negatives -1 and -2 leave -2 in the list. There is no exception, only a wrong result. The faulty line is line 7: if (data.get(i) < 0) data.remove(i);

How do I fix it?

Replace it with: data.removeIf(n -> n < 0);. If you must remove by index, iterate backwards or do not increment after a removal. removeIf avoids the problem completely.

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