I get Concurrent Modification Exception when i try to remove an item from HashMap. I know that removing items during iteration through HashMap will trigger this exception , but i need to replace older item with new one. How can i do this ? Maybe to create a copy of countNumberOfEachCharacter HashMap , and whe iterate through original HashMap to remove item from copy HashMap ?
countNumberOfEachCharacter = new HashMap<Character,Character>();
if (countNumberOfEachCharacter.containsKey(word.charAt(i))) {
System.out.println("This character already exists");
for (Iterator it = countNumberOfEachCharacter.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
if (key.equals(word.charAt(i))) {
int toIncrease = Integer.parseInt(value.toString());
toIncrease++;
System.out.println("key "+key);
System.out.println("increased "+toIncrease);
countNumberOfEachCharacter.remove(word.charAt(i));
char c = Character.forDigit(toIncrease, 10);
countNumberOfEachCharacter.put(word.charAt(i),c);
}
}
}
else {
System.out.println("First time found this character");
char c = Character.forDigit(1, 10);
countNumberOfEachCharacter.put(word.charAt(i),c);
System.out.println("Stored "+word.charAt(i)+" with count "+c);
}
I take it from “replace” (and from the code you’ve quoted) that the key remains the same, it’s just the value that differs. If so, I don’t believe calling
setValueonMap.Entryobjects causes aConcurrentModificationException, so you could do that.Update: Just tested it, and indeed, it works: