ConcurrentModificationException with ListIterator
You'll learn why modifying a list through the list itself (not the iterator) during iteration causes an exception.
The Fail-Fast Behavior
When you're iterating through a List using a ListIterator, Java keeps a close watch on the list's structure. If you modify the list's structure (add or remove elements) through the list's own methods instead of through the iterator's add() or remove() methods, the iterator detects this "external" change and throws a ConcurrentModificationException.
This is called fail-fast behavior—the iterator fails immediately rather than risking unpredictable results from continuing with a modified structure.
Why This Happens
Think of it like editing a document while someone else is reading it aloud. The iterator is reading line-by-line, but if you suddenly delete a paragraph using a different tool, the reader loses their place and can't reliably continue.
Internally, the list maintains a modification count. The iterator stores this count when created. Every time you call list.add() or list.remove(), the count changes. When you call next() or previous() on the iterator, it checks if the count still matches—if not, exception!
What Triggers It
- Calling
list.add(),list.remove(), orlist.clear()while iterating - Any structural modification except through the iterator's own
add()orremove()methods
Safe Practice
Always modify the list through the iterator during iteration:
- Use
iterator.remove()instead oflist.remove() - Use
iterator.add()instead oflist.add()
Key Takeaway: Modifying a list's structure through the list itself (not the iterator) during iteration triggers a ConcurrentModificationException due to fail-fast behavior—always use the iterator's own modification methods to stay safe.