I have the following code
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Arrays.stream("hello how are you".split(" ")).forEach(s -> list.add(s));
Iterator<String> it = list.iterator();
ListIterator<String> lit = list.listIterator();
while (it.hasNext()) {
String s = it.next();
if (s.startsWith("a")) {
it.remove();
} else {
System.out.println(s);
}
}
System.out.println(list);
// {here}
while (lit.hasNext()) {
String s = lit.next();
if (s.startsWith("a")) {
lit.set("1111" + s);
} else {
System.out.println(s);
}
}
System.out.println(list);
}
Here, after iterating through the Iterator
, I try to iterate through the ListIterator
. But the code throws a ConcurrentModificationException
. I do the modification using the ListIterator
only after the Iterator
is done, but why do I get this exception.
When I initalize the ListIterator at {here}
instead at the top, the code runs perfectly.
- Isn't
ConcurrentModificationException
thrown when the list is being modified by two threads simultaneously? - Does initializing the iterator, create a lock on the list ? If yes, then why does Java let us to initialize an
Iterator
after it has already been initialized by anotherIterator
?