Quick revision
The short answer
The for-each loop iterates with the list's Iterator, and names.remove(s) changes the list behind the iterator's back. The removal increases the list's modCount, so the iterator's next step finds a mismatch and throws ConcurrentModificationException. We fix it with an explicit Iterator and it.remove(), or more simply with names.removeIf(String::isBlank), which is clearer and runs in one pass on an ArrayList. Watch out: removing the second-last element does not throw but silently skips the last element.
What to remember
In this answer, we saw that a for-each loop is an Iterator loop, so removing through the list changes modCount behind the iterator, and its next() throws ConcurrentModificationException. Removing the second-last element is the dangerous case: hasNext() only compares the cursor with the size, so the loop ends early and silently skips the last element. We fixed it with Iterator.remove(), which keeps the iterator in sync, and with removeIf(String::isBlank), which is clearer and runs in one pass on an ArrayList.
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 for-each loop iterates with the list's Iterator, and names.remove(s) changes the list behind the iterator's back. The removal increases the list's modCount, so the iterator's next step finds a mismatch and throws ConcurrentModificationException. We fix it with an explicit Iterator and it.remove(), or more simply with names.removeIf(String::isBlank), which is clearer and runs in one pass on an ArrayList. Watch out: removing the second-last element does not throw but silently skips the last element.
Why this question is asked
Removing elements while looping over a collection is one of the most common bugs in Java, and it is sneaky because it sometimes works. Interviewers ask it to see whether we understand what the for-each loop really compiles to and how fail-fast iterators work, and whether we know the modern one-line fix. In this answer, we will see what the loop turns into, reproduce the exception step by step, look at the case where it silently skips an element, and then fix it two ways.
1What the For-Each Loop Really Is
The enhanced for loop over a collection is shorthand. The compiler turns it into an Iterator loop: it asks the list for an iterator, calls hasNext() before each round and next() to get each element.
So there are two parties: the iterator, which is walking the list and keeps its own position, and the list, which we modify directly. The iterator was never told about the removal.
2Reproducing the Exception
ArrayList keeps a counter called modCount, which it increases on every structural change, meaning any change to its size. When the iterator is created, it copies the current modCount into its own field, expectedModCount. Every call to next() first checks that the two still match. If they do not, the list was changed by someone other than the iterator, so the iterator's position can no longer be trusted, and it throws.
8 messages in order. Play them, or step through them one at a time.
Notice that the remove itself succeeds. The exception comes from the following next(), which is why the stack trace points at the loop line and not at the remove call.
3The Case Where It Silently Skips an Element
Now the dangerous variant. hasNext() on an ArrayList iterator does not check modCount; it only compares its cursor, the index of the next element to return, with the list's size. If we remove the second-last element, the size drops to exactly the cursor, hasNext() returns false, and the loop ends normally, without ever looking at the last element.
This is worse than the exception, because it hides the bug. Tests with data that happens to avoid this position pass, and the bad entry slips through in production. So the rule is not to rely on the exception: never modify a collection through the collection while iterating it with for-each.
4Fix 1: Remove Through the Iterator
The iterator has its own remove() method. It removes the element last returned by next() and then updates expectedModCount to match, so the next check passes. To use it, we write the iterator loop explicitly.
This works for every collection that supports removal, and it is the right tool when the loop does more than just remove, such as logging each removed entry. On an ArrayList, though, each it.remove() shifts the rest of the array, so removing many elements from a large list is O(n squared).
5Fix 2: removeIf
Since Java 8, Collection.removeIf(predicate) does the whole job in one call. ArrayList overrides it with an efficient version: it scans once to find the elements to remove, then compacts the survivors in a single pass. So it is O(n) however many elements match.
This is the fix we would choose: it states the intent in one line, it cannot skip elements, and it is the fastest option on an ArrayList. It throws UnsupportedOperationException on immutable lists such as List.of, where we would build a filtered copy instead with names.stream().filter(s -> !s.isBlank()).toList().
6Follow-up questions
Why does the exception say concurrent when there is only one thread?
Concurrent here means a modification that happened during iteration from outside the iterator, not necessarily from another thread. In this example the same thread removes through the list while its own iterator is active. The name is historical and misleads many people.
Does the same bug happen with HashMap or HashSet?
Yes. Their iterators are fail-fast in the same way, so removing from a map while iterating its keySet or entrySet with for-each throws ConcurrentModificationException. The fixes are the same: iterator.remove(), or map.keySet().removeIf(...), map.values().removeIf(...) or map.entrySet().removeIf(...).
Is a plain index loop a safe alternative?
Only if we handle the shifting. After remove(i), the next element moves into position i, so incrementing i skips it. Looping backwards from the end avoids that, but removeIf is simpler and faster.
7Conclusion
In this answer, we saw that a for-each loop is an Iterator loop, so removing through the list changes modCount behind the iterator, and its next() throws ConcurrentModificationException. Removing the second-last element is the dangerous case: hasNext() only compares the cursor with the size, so the loop ends early and silently skips the last element. We fixed it with Iterator.remove(), which keeps the iterator in sync, and with removeIf(String::isBlank), which is clearer and runs in one pass on an ArrayList.
Open with
The for-each loop is compiled into an iterator loop: it calls iterator, then hasNext and next each round. Inside, we call names.remove, which removes through the list, not through the iterator.
Then, if they want more
ArrayList counts structural changes in modCount, and the iterator remembered the value when it was created. So on the next call to next, it sees modCount has changed and throws ConcurrentModificationException. The remove itself succeeds; the failure is on the following step.
There is also a nastier case. hasNext only compares the cursor with the size and does not check modCount, so if the element I remove is the second-last one, the size drops to the cursor, the loop just ends, and the last element is never examined. No exception, but a blank entry is left behind.
So I never rely on the exception. The first fix is to write the iterator loop explicitly and call it.remove, which removes the element last returned by next and updates the expected count, so iteration continues correctly. That works for any collection and is useful if the loop does more than remove.
The second fix, which I would choose, is names.removeIf(String::isBlank). It says what I mean in one line, it cannot skip elements, and ArrayList implements it in a single pass that compacts survivors, so it is O(n), whereas repeated it.remove calls shift the array each time. On an immutable list I would filter into a new list with a stream instead.
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 Collections Framework, overview, java.util, package 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 "Find the bug and fix it in two ways:": https://scrivio-interview-library.netlify.app/java/lists/59680be547/