Quick revision
The short answer
The enhanced for loop runs on a hidden Iterator, and names.remove(s) changes the list behind that iterator's back: the list's modCount goes up, and the iterator's next call to next() sees the mismatch and throws ConcurrentModificationException. The two correct ways are to remove through the iterator itself with it.remove(), or to call names.removeIf(String::isBlank), which is shorter and, on an ArrayList, faster.
What to remember
In this answer, we saw that the enhanced for loop is an Iterator in disguise, and that removing from the list directly raises its modCount, which the iterator detects on the next call to next() and reports with ConcurrentModificationException. We fixed it by removing through the iterator with it.remove(), or with names.removeIf(String::isBlank), which on an ArrayList compacts the array in one O(n) pass instead of shifting elements for every removal. When the original list should stay as it is, filtering into a new list with a stream is a third option.
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 a hidden Iterator, and names.remove(s) changes the list behind that iterator's back: the list's modCount goes up, and the iterator's next call to next() sees the mismatch and throws ConcurrentModificationException. The two correct ways are to remove through the iterator itself with it.remove(), or to call names.removeIf(String::isBlank), which is shorter and, on an ArrayList, faster.
Why this question is asked
Removing elements while looping over a list is one of the first runtime exceptions most Java developers meet, and it keeps coming back in code reviews in new shapes. Interviewers ask it to see whether we understand what the enhanced for loop really compiles to and how ArrayList detects changes, not just whether we remember a fix. In this answer, we will see what the loop turns into, follow modCount to the exception, write the two fixes, compare their cost, and look at a third option when we do not need to change the list at all.
1What the Enhanced for Loop Really Is
The enhanced for loop is syntax sugar. For anything that implements Iterable, the compiler turns it into a loop over an Iterator. Our code and the version below compile to essentially the same thing.
So there is an iterator in play even though we never named it. The trouble is that we remove from the list directly, while the iterator is still walking it, and the iterator was not told.
2How ArrayList Notices the Change
ArrayList keeps a counter called modCount, short for modification count. Every structural change, meaning any add or remove that changes the size, increments it. When we create an iterator, it copies the current value into its own field, expectedModCount. Each call to next() first compares the two, and if they differ, it throws ConcurrentModificationException.
- Iterator copies modCount
expectedModCount=modCount - names.remove(s) runs
modCountgoes up; iterator is not told - Iterator calls next()compares the two counters
- Counters equal?Yesreturn the next elementNothrow ConcurrentModificationException
4 steps in order. Play them, or step through them one at a time.
The check is in next(), so the failure appears one step after the real mistake.
Notice that the exception does not come from remove(). The removal succeeds. It comes from the following next(), which is the first moment the iterator checks. That design exists because the iterator's cursor is now wrong: after the removal, every element has shifted left by one, so continuing would silently skip an element.
3Fix 1: Remove Through the Iterator
Iterator.remove() deletes the element that next() just returned, and because the iterator does the removal itself, it updates its own cursor and its expectedModCount. The list and the iterator stay in agreement.
This is the classic fix and it works for every Collection that supports removal. It is also the right choice when the removal decision needs more than a predicate, for example when we must log each removed name or stop after removing the first five.
4Fix 2: removeIf
Since Java 8, Collection has removeIf(Predicate), which removes every element for which the predicate returns true. It says what we mean in one line.
On an ArrayList, removeIf is also more efficient. Each it.remove() on an ArrayList shifts every later element one place to the left, so removing k elements from a list of n can cost about k times n moves, which is O(n squared) in the worst case. ArrayList.removeIf first finds the elements to remove, then compacts the array in one pass, moving each surviving element at most once. For a list of 100,000 names where half are blank, that is the difference between billions of element moves and about 100,000.
5A Third Option: Build a New List
If we do not need to change the original list, for example because other code holds a reference to it or it is immutable, we can build a filtered copy instead.
Stream.toList(), available since Java 16, returns an unmodifiable list. If the caller needs to keep changing the result, collect into a new ArrayList with Collectors.toCollection(ArrayList::new). The original list is untouched either way.
6Follow-up questions
Would a classic indexed for loop work?
It works only if we adjust the index after each removal, for example by walking backwards from size() - 1 to 0, so that removals do not shift the elements we have yet to visit. Walking forwards with i++ skips the element right after each removed one. It is easy to get wrong, so removeIf is the better choice.
Does this happen with a CopyOnWriteArrayList?
No exception is thrown, because its iterator walks a snapshot of the array taken when the loop started, and removing from the list creates a new array. The loop still visits every original element. But each removal copies the whole array, so it is slow for large lists, and its iterator's own remove() throws UnsupportedOperationException.
Is ConcurrentModificationException only about threads?
No. Despite its name, it is usually thrown in single-threaded code like this one. It means the collection was structurally changed while an iterator was in use, by any code other than that iterator.
7Conclusion
In this answer, we saw that the enhanced for loop is an Iterator in disguise, and that removing from the list directly raises its modCount, which the iterator detects on the next call to next() and reports with ConcurrentModificationException. We fixed it by removing through the iterator with it.remove(), or with names.removeIf(String::isBlank), which on an ArrayList compacts the array in one O(n) pass instead of shifting elements for every removal. When the original list should stay as it is, filtering into a new list with a stream is a third option.
Open with
The enhanced for loop compiles to an Iterator, so we are removing from the list while an iterator is walking it, and not through that iterator. ArrayList keeps a modCount that every structural change increments, and the iterator remembers the value it started with. names.remove(s) succeeds and bumps modCount, and on the next call to next the iterator sees that the counts differ and throws ConcurrentModificationException, because its cursor would otherwise be pointing at the wrong place after the elements shifted.
Then, if they want more
The first fix is to use the iterator explicitly: get names.iterator(), loop with hasNext, and when it.next() is blank call it.remove(). That removes the element just returned and keeps the iterator's expected count in step. The second fix, and the one I'd normally use, is names.removeIf(String::isBlank).
It's one line, it says what we mean, and on an ArrayList it's faster: removing through the iterator shifts the tail of the array on every removal, which can be quadratic, while removeIf marks what to remove and compacts the array in one linear pass.
If I don't actually need to change the list, I'd build a new one instead, with a stream filter and toList, which also works when the original is immutable.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 16, 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 "This code throws ConcurrentModificationException:": https://scrivio-interview-library.netlify.app/java/iteration/8adf78438e/