Fast-Fail : meaning that if they detect
that the collection has changed since iteration began, they throw the unchecked
ConcurrentModificationException
.
I have written a test example to demonsterate this:
String hi = "Hi";
list.add(hi);
list.add("Buy");
System.out.println("list before: " + list);
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String string = iterator.next();
list.add("Good");
}
the output is:
list before: [Hi, Buy]
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at thread.CollectionTest.main(CollectionTest.java:19)
which is expected. However, when an element is removed, the exception is not thrown:
List<String> list = new ArrayList<>();
String hi = "Hi";
list.add(hi);
list.add("Buy");
System.out.println("list before: " + list);
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String string = iterator.next();
list.remove(hi);
}
Output:
list before: [Hi, Buy]
list after: [Buy]
Why is that? both cases the list is modified.