The modCount Field in ArrayList
You'll learn how ArrayList internally tracks structural changes to enable fail-fast iterator behavior.
How ArrayList Tracks Modifications
Whenever you add, remove, or structurally modify an ArrayList, the collection needs to know that it changed. ArrayList tracks this with an internal counter called modCount (short for "modification count"). Every structural modification—like add(), remove(), or clear()—increments this counter by one.
Think of modCount like a version number on a document. Each edit bumps the version. If you started reading version 5 but someone changes it to version 6, you know the document changed while you were reading.
How Iterators Use modCount
When you create an iterator from an ArrayList, that iterator captures the current modCount value in its own expectedModCount field. Every time you call next() or hasNext(), the iterator checks:
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
If the counts don't match, someone modified the ArrayList outside the iterator, and the iterator throws ConcurrentModificationException—this is the fail-fast behavior you learned about in the previous lesson.
What Triggers modCount Changes
- Increments modCount:
add(),remove(),clear(),addAll(),removeAll(), etc. - Does NOT change modCount:
get(),set(),contains(),size()(these aren't structural changes)
Note that iterator.remove() is safe because it updates both the ArrayList's modCount and the iterator's expectedModCount in sync.
Key Takeaway: The modCount field is ArrayList's internal version counter that increments with every structural modification, allowing iterators to detect concurrent changes and fail fast with ConcurrentModificationException.