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.
iterator.next()or try with 3 entries ...nextthen remove, then hasNext checks whether the nextnextcall would return an element. It would not, so it returns false. And the nextnextcall is not executed that would finally throw the exception. That would be my explanation, though as I said, not 100% sure. So if you had 3 elements, hasNext would return true and the following next would throw.next()method will lookcheckForComodification. If theif (modCount != expectedModCount)then will throw.ConcurrentModificationException