Safe Removal During Iteration — Interview Questions
⚡ 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.
☕Coffee Chat Question
Concept Made Simple
“How do you safely modify a collection while iterating it, and what causes ConcurrentModificationException?”
🧠Mind Map Answer
Remember It Faster
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.
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.
⌨️Hands-on Keyboard
Learn by Doing
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]
🔥What If?
Think Beyond the Expected
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:
⚠️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
- 1How do fail-fast and fail-safe iterators differ internally?
- 2How does CopyOnWriteArrayList avoid CME?
- 3Why is removeIf preferable to a manual loop?
🧩Related Technologies
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?
⭐ Featured Products
Support our platform by exploring our recommended products.
As an Amazon affiliate, purchases through these links may earn us a small commission — at no extra cost to you. It helps keep Full Stack Interview Guru free.