Iterator fail-fast property checks for any modification in the
structure of the underlying collection everytime we try to get the
next element. If there are any modifications found, it throws
ConcurrentModificationException. All the implementations of Iterator
in Collection classes are fail-fast by design except the concurrent
collection classes like ConcurrentHashMap and CopyOnWriteArrayList.
Source: Google
You'll better understand with an example written below:-
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class IteratorExp {
public static void main(String... q) {
//CASE - ONE
List<String> strList = new ArrayList<>(Arrays.asList("a", "b", "c"));
Iterator<String> itr = strList.iterator();
/*
* strList.add("e"); strList.add("f"); strList.add("g");
*/
while (itr.hasNext()) {
System.out.println(itr.next());
}
/*
* Exception in thread "main" java.util.ConcurrentModificationException
* at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at
* java.util.ArrayList$Itr.next(Unknown Source) at
* IteratorExp.main(IteratorExp.java:14)
*/
//CASE - TWO
List<Integer> intList = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0));
Iterator<Integer> itrOne = intList.iterator();
Iterator<Integer> itrTwo = intList.iterator();
for (; itrOne.hasNext();) {
if (itrOne.next().equals(5)) {
itrOne.remove(); // #1
//intList.remove(itrOne.next()); // #2
}
}
for (; itrTwo.hasNext();) {
if (itrTwo.next().equals(5)) {
itrTwo.remove(); // #1
//intList.remove(itrTwo.next()); // #2
}
}
/*
* Exception in thread "main" java.util.ConcurrentModificationException
* at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at
* java.util.ArrayList$Itr.next(Unknown Source) at
* IteratorExp.main(IteratorExp.java:35)
*/
}
}