HashMap's Iterator to prevent concurrent modification

257 views Asked by At

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?

1

There are 1 answers

0
Mureinik On BEST ANSWER

As you guessed, you need an iterator for removing items during iteration. The way to do it with a Map is to iterate the entrySet() (or, alternatively, the keySet(), if you only need to evaluate the key):

Iterator<Map.Entry<String, String>> entryIter = map.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String, String> entry = iter.next();
    iter.remove(); // Probably guard this by some condition?
}