Safe Removal During Iteration — Interview Questions
Reviewed by Gurusankar M.
Short Answer
Standard collections are fail-fast: they track a modCount, and if it changes during iteration (because you called list.remove() while looping) the next iterator step throws ConcurrentModificationException — even in a single thread. Safe options: use Iterator.remove(), use Collection.removeIf() (cleanest), collect-then-remove, or use a concurrent/copy-on-write collection whose iterators are weakly consistent and never throw.
On this page
Concept Made Simple
Coffee Chat Question
“How do you safely modify a collection while iterating it, and what causes ConcurrentModificationException?”
Remember It Faster
Mind Map Answer
CME is usually not about threads — it's a single-thread bug: modifying the collection directly (not through the iterator) while a for-each loop is running. The iterator detects the structural change via modCount and fails fast.
- Cause
- Structural change during iteration (modCount)
- Iterator.remove()
- Safe removal during a manual loop
- removeIf(pred)
- Cleanest bulk conditional removal
- CopyOnWrite / concurrent
- Weakly-consistent, never throws
For-each is just syntactic sugar over an Iterator, so calling list.remove(x) inside it bumps modCount behind the iterator's back → CME on the next next(). Going through the iterator (or removeIf) keeps modCount in sync.
Key takeaway: never structurally modify a fail-fast collection directly while iterating. Use removeIf for bulk deletes, Iterator.remove for manual loops, or a concurrent collection when you truly iterate under concurrency.
Learn by Doing
Hands-on Keyboard
List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5));
// ❌ throws ConcurrentModificationException
// for (Integer n : nums) if (n % 2 == 0) nums.remove(n);
// ✅ cleanest — bulk conditional removal
nums.removeIf(n -> n % 2 == 0);
// ✅ manual loop alternative
Iterator<Integer> it = nums.iterator();
while (it.hasNext()) if (it.next() > 3) it.remove();
System.out.println(nums);[1, 3]
Think Beyond the Expected
What If?
Does ConcurrentModificationException mean there was a concurrency (multi-thread) bug?
Not necessarily — despite the name, it's most often thrown in purely single-threaded code that modifies a collection directly during a for-each loop. It's a fail-fast guard based on a modCount check, a best-effort detector of structural changes, not a thread-safety mechanism. (It CAN also fire when another thread mutates the collection mid-iteration, but you should never rely on it to detect that — use a proper concurrent collection instead.)
Real World
Filtering a list in place — removing expired sessions, invalid records, completed jobs — is where developers hit CME constantly. removeIf is the modern one-liner; CopyOnWriteArrayList backs listener lists that are iterated far more than mutated; ConcurrentHashMap's weakly-consistent iterator lets background sweeps run without throwing.
Interviewer's Expectation
Keywords they're listening for:
- fail-fast via modCount
- CME often single-threaded
- Iterator.remove / removeIf
- for-each is iterator sugar
- concurrent collections are weakly consistent
Common Mistakes
- Calling list.remove() inside a for-each loop
- Assuming CME implies a threading bug
- Using a synchronized wrapper and still iterating without a lock
Best Practices
- Prefer removeIf for conditional bulk removal
- Use Iterator.remove() in manual loops
- Use concurrent collections when iterating under real concurrency
Follow-up Questions
- How do fail-fast and fail-safe iterators differ internally?
- How does CopyOnWriteArrayList avoid CME?
- Why is removeIf preferable to a manual loop?
Continue Learning with AI
Take this question deeper with your favourite AI assistant. Pick a depth, copy the prompt, or open it directly — AI is your learning companion, not a shortcut.
Plain-language foundations
I'm preparing for a software engineering interview and want to understand this from scratch, as a beginner. Topic: Collections (Advanced Java) Interview question: "How do you safely modify a collection while iterating it, and what causes ConcurrentModificationException?" Please: 1. Explain the core idea in simple, plain language, using an everyday analogy. 2. Define any technical terms you use. 3. Walk through one small, concrete example. 4. Finish with a single sentence I can easily remember. Keep the tone friendly and assume I'm new to this topic.
Was this answer helpful?
Affiliate links
Tools for Your Developer Workspace
Equipment for a comfortable, productive setup.
As an Amazon Associate I earn from qualifying purchases.
- MonitorView on Amazon : BenQ EW2790U 27-inch Monitor (opens in a new tab)
BenQ EW2790U 27-inch Monitor
- LaptopView on Amazon : Acer Aspire One Laptop (opens in a new tab)
Acer Aspire One Laptop
- Office ChairView on Amazon : Wakefit Gravita Ergonomic Office Chair (opens in a new tab)
Wakefit Gravita Ergonomic Office Chair