Suppose a map contains integer keys, and a list of strings as its value. Then, I CAN’T do this :
for (Map.Entry<Integer, List<String>> entry : map.entrySet()){
for (String string : entry.getValue()){
if (string.startsWith("a")){
entry.getValue().remove(string);
}
}
}
It throws ConcurrentModificationException. But if I do the following :
for (Map.Entry<Integer, List<String>> entry : map.entrySet()){
entry.setValue(new ArrayList<String>());
}
This works perfectly. Aren’t we modifying the underlying map even now ?
The problem has nothing to do with the
Map, only the way you’re using the value list. The following will fail with anyArrayList:The reason for this is discussed in the Javadoc of
ArrayList:(To put it another way: if you remove the element from the list, the iterator might not be pointing to the right index in the underlying array anymore. So instead of allowing you to use a potentially corrupted iterator, it throws a
ConcurrentModificationExceptionas a courtesy to let you know that you need to redesign your program.)A simple fix is to use