Java.Collections.What about fail fast in list iterator

💥 Is ListIterator fail-fast?

Yes, ListIterator is fail-fast, just like Iterator.

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 internal modCount variable.
  • ListIterator captures this value when created.
  • On every next(), previous(), remove(), etc., it checks if the modCount is still the same.
  • If someone else (outside the iterator) modifies the list, modCount changes → boom 💥

💬 Recap:

FeatureListIterator
Fail-fast?✅ Yes
Safe to modify via self✅ Yes (add(), remove(), set())
Unsafe to modify list directly during iteration❌ Throws ConcurrentModificationException
This entry was posted in Без рубрики. Bookmark the permalink.