javalistiteratorrobustness

Java ListIterator Robustness


I hava a simple LinkedList in Java, that has, say, 10 elements. At that state, I get an ordinary ListIterator, say .listIterator(3). If I then insert/remove other elements into the list, without touching the element on which I have the ListIterator (nor the iterator), will the ListIterator still be valid?


Solution

  • If you modify a java.util.LinkedList outside of the ListIterator's own methods then the iterator is adulterated and will throw ConcurrentModificationException if you try to use it again.

    This is covered in the javadoc for linked list:

    The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the Iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.