I have a simple HashMap
algorithm:
HashMap<Integer, Integer> map = new HashMap<>();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
Iterator<Integer> it = map.keySet().iterator();
while(it.hasNext()) {
Integer key = it.next();
if (key.equals(2)) {
map.put(1, 2);
}
}
and this is working fine. But when I will modify the condition body to:
if (key.equals(2)) {
map.put(0, 2); // changed index '1' to '0'
}
it's always throwing java.util.ConcurrentModificationException
. The same is happening for key values lesser than 0
.
What am I missing?
Edit
Seems that if I will remove the third Map
element:
map.put(1, 1);
map.put(2, 2);
// map.put(3, 3);
it's working fine