当我尝试从 HashMap 中删除项目时,出现并发修改异常。我知道在通过 HashMap 迭代期间删除项目会触发此异常,但我需要用新项目替换旧项目。我怎样才能做到这一点 ?也许创建 countNumberOfEachCharacter HashMap 的副本,然后迭代原始 HashMap 以从副本 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);
}
最佳答案
在Collection
上进行迭代时,您只能使用Iterator#remove
方法删除元素。这也记录在 HashMap
The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future
此外,对于您想要执行的操作(=更新值),您不必删除它。只需使用该键和更新后的值调用 put
即可更新该值,如 HashMap#put
方法的 javadoc 中所述
Associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced.
关于java - 在迭代期间替换/更改 HashMap 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8776722/