💥 Is ListIterator
fail-fast?
✅ Yes,
ListIterator
is fail-fast, just likeIterator
.
It monitors structural changes to the list during iteration using an internal modCount, and if the list is modified outside of the iterator while iterating, it throws:
ConcurrentModificationException
🧪 Example: Fail-fast behavior in ListIterator
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("Go");
ListIterator<String> lit = list.listIterator();
// External modification
list.add("Rust"); // ❌ Structural change outside iterator
while (lit.hasNext()) {
System.out.println(lit.next()); // 💥 ConcurrentModificationException
}
✅ Safe Modification with ListIterator
When you modify the list using the ListIterator
itself, it’s safe — because the iterator is aware of the change and updates modCount
internally.
List<String> list = new ArrayList<>(List.of("A", "B", "C"));
ListIterator<String> lit = list.listIterator();
while (lit.hasNext()) {
String val = lit.next();
if (val.equals("B")) {
lit.set("Beta"); // ✅ safe replacement
lit.add("Bravo"); // ✅ safe addition
}
}
System.out.println(list); // [A, Beta, Bravo, C]
🧠 Under the Hood: How fail-fast works
- Java lists (like
ArrayList
) maintain an internalmodCount
variable. ListIterator
captures this value when created.- On every
next()
,previous()
,remove()
, etc., it checks if themodCount
is still the same. - If someone else (outside the iterator) modifies the list,
modCount
changes → boom 💥
💬 Recap:
Feature | ListIterator |
---|---|
Fail-fast? | ✅ Yes |
Safe to modify via self | ✅ Yes (add() , remove() , set() ) |
Unsafe to modify list directly during iteration | ❌ Throws ConcurrentModificationException |