The following piece of code, while executed by a single thread, throws a ConcurrentModificationException
on line 4:
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
for (String key : map.keySet()) { // Here
map.remove(key);
}
I couldn't find any Map.iterator()
or Map.mapIterator()
method on HashMap
Javadoc.
What should I do?
As you guessed, you need an
iterator
for removing items during iteration. The way to do it with aMap
is to iterate theentrySet()
(or, alternatively, thekeySet()
, if you only need to evaluate the key):