简体   繁体   English

HashMap中的并发修改异常

[英]Concurrent Modification Exception in HashMap

I'm writing this program in Java and I'm getting a java.util.ConcurrentModificationException. 我正在用Java编写这个程序,我得到了一个java.util.ConcurrentModificationException。 The code excerpt is given below, please let me know if more code is required. 代码摘录如下,如果需要更多代码,请告诉我。

for (String eachChar : charsDict.keySet()) {
    if (charsDict.get(eachChar) < 2) {
        charsDict.remove(eachChar);
    }
}

charsDict is defined as charsDict定义为

Map<String, Integer> charsDict = new HashMap<String, Integer>();

Please help me :) 请帮我 :)

You're not allowed to remove elements from the map while using its iterator. 在使用迭代器时,不允许从地图中删除元素。

A typical solution to overcome this: 解决此问题的典型解决方案:

List<String> toBeDeleted = new ArrayList<String>();
for (String eachChar : charsDict.keySet()) {
    if (charsDict.get(eachChar) < 2) {
        toBeDeleted.add(eachChar);
    }
}

for (String eachChar : toBeDeleted) {
    charsDict.remove(eachChar);
}

You need to use the remove method of the iterator: 您需要使用迭代器的remove方法:

for (Iterator<String> it = charsDict.keySet().iterator(); it.hasNext();) {
    String eachChar = it.next();
    if (charsDict.get(eachChar) < 2) {
        it.remove();
    }
}

Also note that since you need to access the key AND the value, it would be more efficient to use entrySet instead : 另请注意,由于您需要访问键和值, 因此使用entrySet会更有效

for (Iterator<Map.Entry<String, Integer>> it = charsDict.entrySet().iterator(); it.hasNext();) {
    Map.Entry<String, Integer> e = it.next();
    String eachChar = e.getKey();
    int value = e.getValue();
    if (value < 2) {
        it.remove();
    }
}

And finally it appears that the key is actually not used , so the loop becomes: 最后看来密钥实际上没有使用 ,所以循环变为:

for (Iterator<Integer> it = charsDict.values().iterator(); it.hasNext();) {
    if (it.next() < 2) {
        it.remove();
    }
}

See also this related post . 另见这篇相关文章

如果在线程之间进行sahred,则使用ConcurrentHashMap可能是更好的选择... Iterator不是线程安全的,你应该创建一个新的迭代器,它在线程之间使用相同的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM