Scrivio Interview library
DebuggingFoundations5 min read · updated 12 November 2026

Why does this code NOT throw ConcurrentModificationException, and why is it still a bug?

Java
List<String> l = new ArrayList<>(List.of("a", "b", "c"));
for (String s : l) {
if (s.equals("b")) l.remove(s);
}
System.out.println(l);

After "b" is removed, the list's size drops to 2 while the iterator's cursor is already at 2, so hasNext(), which only checks cursor != size, returns false and the loop ends before next() ever gets to check modCount. The code prints [a, c], but "c" was never examined, and with other data the same code throws ConcurrentModificationException, so its behaviour depends on where the match is. Iterator.remove() or removeIf makes it correct.

Why this question is asked

This puzzle appears in interviews because it breaks the rule most people remember, that removing in a for-each loop always throws. Understanding why it does not throw here requires knowing exactly how ArrayList's iterator works, and that knowledge is what lets us explain the many real bugs where a loop quietly skips elements. In this answer, we will recap the iterator's two fields, trace the loop step by step, see what changes with other data, and fix it.

1A Quick Recap of ArrayList's Iterator

ArrayList's iterator keeps a field called cursor, the index of the next element to return, starting at 0. Its hasNext() is simply cursor != size: there is another element as long as the cursor has not reached the end. Its next() first checks for concurrent modification, comparing the list's modCount with the expectedModCount it saved at creation, then returns the element at cursor and adds one to cursor.

Notice the asymmetry: only next() checks modCount. hasNext() does no check at all. That one detail explains the whole puzzle.

2Tracing the Loop Step by Step

The enhanced for loop calls hasNext() and then next() on each turn. Here is every call with the values of cursor and size.

Java
List<String> l = new ArrayList<>(List.of("a", "b", "c"));
for (String s : l) { if (s.equals("b")) l.remove(s); }
System.out.println(l);
// hasNext(): cursor 0 != size 3 -> true
// next(): modCount ok, returns "a", cursor = 1
// hasNext(): cursor 1 != size 3 -> true
// next(): modCount ok, returns "b", cursor = 2
// l.remove("b"): "c" shifts to index 1, size = 2, modCount + 1
// hasNext(): cursor 2 != size 2 -> false, loop ends
// prints [a, c]
Iterator state during the loop
StepcursorsizeResult
next() returns "a"13fine
next() returns "b"23fine
l.remove("b")22modCount changed, "c" now at index 1
hasNext()22false: loop ends, "c" never examined

The removal does change modCount, so the iterator is in an invalid state. But the check that would detect it lives in next(), and next() is never called again: hasNext() said there was nothing left, because the removal shrank the list to exactly where the cursor was standing.

And that is also the bug. After the removal, "c" moved from index 2 to index 1, behind the cursor. The loop never looked at it. The output [a, c] looks right only because "c" did not need removing.

3Why the Same Code Throws With Other Data

The quiet ending happens only when the removed element is the second-to-last one. In every other position the loop continues, calls next(), and the modCount check fires.

Java
List<String> l1 = new ArrayList<>(List.of("b", "a", "c"));
for (String s : l1) { if (s.equals("b")) l1.remove(s); }
// after removing "b": cursor 1, size 2, hasNext() true, next() -> ConcurrentModificationException
List<String> l2 = new ArrayList<>(List.of("a", "b", "b"));
for (String s : l2) { if (s.equals("b")) l2.remove(s); }
// removes the first "b": cursor 2, size 2, loop ends; prints [a, b], a "b" survives

The second example shows the real danger. It runs without an exception and gives a wrong answer: the task was to remove every "b", and one is left. So this code is not safe in the cases where it does not throw. Its behaviour depends on where the matching elements are, which means it can pass every test and fail in production on different data. Also note that the fail-fast check is described in the Javadoc as best-effort for exactly this kind of reason; it is a bug detector, not a guarantee.

4Making It Correct

The fix is the same as for the case that throws: remove through the iterator, which updates the cursor and expectedModCount together, or let the list do the whole job.

Java
Iterator<String> it = l2.iterator();
while (it.hasNext()) {
if (it.next().equals("b")) it.remove(); // cursor moves back, nothing skipped
}
System.out.println(l2); // [a]
l2.removeIf(s -> s.equals("b")); // same result in one line, one pass
l2.removeAll(List.of("b")); // also works: removes every "b"

Iterator.remove() steps the cursor back to the removed element's index, so the element that shifted into that place is the next one returned. removeIf is the clearest form and, on ArrayList, compacts the array in a single pass.

5Follow-up questions

Why doesn't hasNext() check modCount too?

It could, but the iterator's design checks only where it hands out an element, which keeps hasNext() cheap. The Javadoc makes no promise that every concurrent modification will be detected, so adding a check there would narrow the gap but not close it in general.

Does the same thing happen with a HashMap?

HashMap's iterator works differently: it finds the next entry ahead of time, and its hasNext() checks whether that pre-found entry exists. Removing during iteration usually throws on the next call to next(), but removing when the iterator has already found no next entry can again end the loop quietly. The fix is the same: iterator.remove() or entrySet().removeIf().

Would a LinkedList behave the same way?

LinkedList's iterator tracks a nextIndex and checks hasNext() as nextIndex < size, so removing the second-to-last element through the list has the same quiet ending. The details differ by implementation, which is one more reason never to rely on the exception.

6Conclusion

In this answer, we saw why removing "b" from [a, b, c] inside a for-each loop does not throw: ArrayList's hasNext() only compares the cursor with the size, the removal shrinks the size to the cursor's value, and the loop ends before next() can check modCount. The result [a, c] hides the fact that "c" was never examined, and with the match in another position the code either throws or leaves elements behind. Iterator.remove() or removeIf makes the code correct for every position.

What to say in the interviewAbout 80 seconds aloud

Open with

It doesn't throw because of how ArrayList's iterator checks. The modCount check is only in next; hasNext is just cursor not equal to size. Walking through it: next returns a, cursor is 1; next returns b, cursor is 2.

Then, if they want more

Then we remove b, so c shifts down to index 1, size becomes 2, and modCount increases. Now hasNext compares cursor 2 with size 2, returns false, and the loop ends. next is never called again, so the modification is never detected. It prints [a, c], which looks right, but c was never examined; it shifted behind the cursor.

That's why it's still a bug: the behaviour depends on where the match is. If b were first, the loop would continue and next would throw ConcurrentModificationException. And with a list like a, b, b, it would remove only the first b, end quietly, and leave the second one in the list, which is a wrong result with no error.

The fail-fast check is best-effort, so its absence tells us nothing about correctness. The fix is to remove through the iterator with it.remove, which moves the cursor back so nothing is skipped, or simply l.removeIf(s -> s.equals("b")), which is clearer and does a single pass over the array.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Why does this code NOT throw ConcurrentModificationException, and why is it still a bug?": https://scrivio-interview-library.netlify.app/java/iteration/cd8e47a240/