Quick revision
The short answer
The enhanced for loop runs on an Iterator behind the scenes, and calling names.remove(s) changes the list without telling that iterator. ArrayList counts structural changes in a field called modCount, and the iterator's next() call sees that the count changed and fails fast with ConcurrentModificationException. The fix is names.removeIf(String::isBlank), or an explicit Iterator whose own remove() method we call. Be careful when testing: removing the second-to-last element often does not throw, because hasNext() returns false first, which hides the bug.
What to remember
In this answer, we saw that the enhanced for loop iterates through an Iterator, and that removing through the list increases modCount, so the iterator's next call to next() fails fast with ConcurrentModificationException. We saw why removing the second-to-last element escapes the check, silently skipping the last element, and we fixed the code with removeIf, or with an explicit Iterator and its own remove() method.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The enhanced for loop runs on an Iterator behind the scenes, and calling names.remove(s) changes the list without telling that iterator. ArrayList counts structural changes in a field called modCount, and the iterator's next() call sees that the count changed and fails fast with ConcurrentModificationException. The fix is names.removeIf(String::isBlank), or an explicit Iterator whose own remove() method we call. Be careful when testing: removing the second-to-last element often does not throw, because hasNext() returns false first, which hides the bug.
Why this question is asked
Removing items from a list while looping over it is one of the first bugs most Java developers write, and the exception name is confusing, because there is often only one thread involved. Interviewers ask it because the explanation shows whether we know what the enhanced for loop really compiles to, and the strange case where the bug does not throw is a good test of whether we understand rather than memorise. In this answer, we will see what the loop turns into, how the fail-fast check works, why one position escapes the check, and then look at the two correct fixes.
1What the Enhanced for Loop Really Is
The enhanced for loop, for (String s : names), is a shorthand. For anything that is Iterable, the compiler turns it into a loop over an Iterator: it asks the list for an iterator, calls hasNext() to see if there is another element, and calls next() to get it.
Notice that the removal goes through names, the list, not through it, the iterator. The iterator keeps its own position, and nobody told it that the list just got shorter.
2How the Fail-Fast Check Works
ArrayList keeps an int field called modCount, short for modification count, which it increases on every structural change, meaning any add or remove that changes the size. When we create an iterator, it copies the current value into its own field, expectedModCount. Every call to next() first compares the two. If they differ, the list was changed by someone other than the iterator, and the iterator's position may now point at the wrong element, so it throws ConcurrentModificationException at once instead of returning wrong data.
That is what fail-fast means: it is better to stop with an exception than to skip or repeat elements silently. The word concurrent refers to the modification happening during the iteration, not to threads, which is why a single thread can trigger it. The check is a best-effort safety net, not a guarantee, and the next section shows a case it misses.
7 messages in order. Play them, or step through them one at a time.
The iterator only notices the change at its next call to next().
3Why Removing the Second-to-Last Element Does Not Throw
ArrayList's iterator decides whether there is more to read with a simple test: hasNext() returns cursor != size, where cursor is the index of the next element to return. If we remove the second-to-last element, the size drops by one at exactly the moment the cursor reaches the new size. hasNext() returns false, the loop ends normally, and next() is never called, so the modCount check never runs.
Notice the danger. The test passes, the output looks right, and we conclude the code works. But the loop silently skipped the last element. With the input ["ann", " ", " "], the result is [ann, ] with one blank left in it. So this case does not mean the code is correct; it means the safety net missed it.
4Fix 1: Use removeIf
Since Java 8, every Collection has removeIf, which takes a condition and removes every element that matches. ArrayList implements it efficiently: it first marks the elements to remove and then compacts the array in one pass, so it is both correct and faster than removing elements one by one.
This is the fix we would choose in almost every case. It says what we mean in one line, and there is no loop to get wrong.
5Fix 2: Remove Through the Iterator
If we need more than a condition, for example logging each removed name or stopping after the first few, we write the loop with an explicit Iterator and call its remove() method. Iterator.remove() deletes the element that next() just returned and updates the iterator's own cursor and expectedModCount, so the next check still passes.
Notice that we call it.remove(), not names.remove(s). That one change is the whole fix. A third option, building a new filtered list with names.stream().filter(s -> !s.isBlank()).toList(), avoids modifying the original at all, which is often the cleanest when nothing else holds a reference to the list.
6Follow-up questions
Does CopyOnWriteArrayList avoid the exception?
Yes. Its iterator reads a snapshot of the array taken when the loop started, so changes made during the loop never affect it and it never throws. But every change copies the whole array, which suits lists that are read far more often than written, such as listener lists, and not this kind of clean-up.
Is ConcurrentModificationException only about multiple threads?
No. Here it is thrown in a single thread. With several threads modifying a plain ArrayList, the check may catch the problem, but it is not guaranteed to, and the real fix there is proper synchronisation or a concurrent collection, not relying on the exception.
Why does the iterator not just adjust itself after names.remove()?
Because the list does not know which iterators exist or where they are. A change made through the list could be anywhere, before or after the cursor, so the iterator cannot safely guess. Failing fast is the only safe reaction.
7Conclusion
In this answer, we saw that the enhanced for loop iterates through an Iterator, and that removing through the list increases modCount, so the iterator's next call to next() fails fast with ConcurrentModificationException. We saw why removing the second-to-last element escapes the check, silently skipping the last element, and we fixed the code with removeIf, or with an explicit Iterator and its own remove() method.
Open with
The enhanced for loop is compiled into a loop over an Iterator, with hasNext and next. When I call names.remove(s), I change the list behind that iterator's back.
Then, if they want more
ArrayList counts structural changes in a field called modCount, and the iterator remembered the value it saw when it was created. On the next call to next it compares the two, sees they differ, and throws ConcurrentModificationException, failing fast rather than skipping or repeating elements. It happens in a single thread; concurrent here just means modified during iteration.
The simplest fix is names.removeIf(String::isBlank), which is correct and also efficient because ArrayList compacts the array in one pass. If I need to do more per element, I use an explicit Iterator and call iterator.remove, which keeps the iterator's cursor and expected count in step with the list.
One trap I would point out is that removing the second-to-last element usually does not throw. After the removal the cursor equals the new size, so hasNext returns false and next is never called. The loop just ends, silently skipping the last element, so a test with that input can pass and hide the bug.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8
- 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.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
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 "This code throws ConcurrentModificationException. Why, and how do you fix it?": https://scrivio-interview-library.netlify.app/java/operators-and-control-flow/76502fc693/