How do you remove elements from a collection while iterating it, and what makes an iterator fail-fast?
Structural modification through the collection during a for-each invalidates the iterator, which detects it by comparing a modification counter and throws ConcurrentModificationException. Remove through the iterator, or use removeIf, or pick a collection whose iterator is weakly consistent instead.
Answer
Short answer
In Java, remove elements while iterating by using Iterator.remove(), Collection.removeIf(...), or a collection whose iterator is designed for concurrent changes. Removing through the collection inside a for-each loop changes the collection's structure behind the iterator, so fail-fast iterators usually throw ConcurrentModificationException. That exception is a bug detector, not a correctness guarantee.
Was this answer helpful?
Likely follow-ups
- Why does removing the second-to-last element of an ArrayList in a for-each sometimes not throw?
- What does the iterator of ConcurrentHashMap guarantee about entries added after iteration begins?
- Why does CopyOnWriteArrayList's iterator not support remove?
- How would you safely remove entries from a Map while iterating it?
Related questions
- How do generators reduce memory use, and when are they the wrong choice?mediumAlso on iterators5 min
- You build a LINQ query, then change the list it came from, then enumerate it. What do you get?mediumAlso on iterators5 min
- Build an in-memory key-value store with per-key TTL, plus a snapshot operation that gives a consistent copy while writes keep coming in.hardAlso on copy-on-write6 min
- You need a random number from 1 to 6 and you wrote rand() % 6. What is wrong with that, and when does it stop being merely wrong and become a vulnerability?mediumSame kind of round: concept4 min