gpt4 book ai didi

java - Map 和 Hashtable 的 ConcurrentModification 异常

转载 作者:行者123 更新时间:2023-11-29 09:38:03 24 4
gpt4 key购买 nike

在我的应用程序中,我使用了一个 Map 来存储 POJO 对象。根据要求,我需要遍历 Map 的 keySet 并删除不需要任何修改的对象。

考虑下面的代码:

 public void remove(Map<String,User> removeUser){
Set<String> keySet = removeUser.keySey();
User user = null;

for(String key : keySet){
user = (user) removeUser.get(key);

if(!user.isActive()){
removeUser.remove(key);
}
}

}

在上面的代码中,当我在删除对象后尝试获取用户对象时出现 ConcurrentModificationException。

谁能告诉我为什么会这样?

我没有使用过多线程。所以无法理解它从哪里产生了 ConCurrentModification 异常。

我试过HashMap和Hashtable,问题依旧。

最佳答案

from where it generated ConCurrentModification Exception.

它来自您在遍历其 KeySet 时尝试从 Map 中删除该元素的行。

if(!user.isActive()){
removeUser.remove(key); // This is the problem
}

你不应该那样做。如果您想修改CollectionMap,请使用iterator


看到这篇非常好的帖子 - efficient-equivalent-for-removing-elements-while-iterating-the-collection解释修改您迭代的集合时可能出现的问题。


这是一个简单的代码,解释了如何在这里使用它:-

    Map<String, Integer> map = new HashMap<String, Integer>() {
{
put("a", 1);
put("b", 2);
put("c", 3);
}
};

Iterator<String> iterate = map.keySet().iterator();

while (iterate.hasNext()) {
int i = map.get(iterate.next());

if(i > 1) {
iterate.remove();
}
}

System.out.println(map);

输出:-

{a=1}

关于java - Map 和 Hashtable 的 ConcurrentModification 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13453217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com