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?
Asked
Active
Viewed 86 times
2

Vlladz
- 185
- 1
- 12
-
This will depend on, and be documented in, your implementation of `List`. In the general case, no. – chrylis -cautiouslyoptimistic- Apr 10 '18 at 23:19
-
I was hoping I could avoid implementing a linkedlist myself that has such behavior... I guess I will have to do so, sadly.. – Vlladz Apr 10 '18 at 23:26
1 Answers
5
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.

Affe
- 47,174
- 11
- 83
- 83
-
s/will/may/ (does not apply to `CopyOnWriteArrayList`) – chrylis -cautiouslyoptimistic- Apr 10 '18 at 23:20
-
Ye I just tried it myself, after I posted the question I realized I could simply test it, wasn't thinking about it throwing an exception.. Thanks anyway :) – Vlladz Apr 10 '18 at 23:23