Fast-Fail : this means that if they discover that the collection has changed since the start of the iteration, they throw an unchecked ConcurrentModificationException .
I wrote a test case to demonstrate 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"); }
output:
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 item is deleted, an 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? in both cases the list has been changed.
source share