gpt4 book ai didi

java - LinkedHashMap -> java.util.ConcurrentModificationException

转载 作者:行者123 更新时间:2023-12-02 08:41:15 26 4
gpt4 key购买 nike

执行以下代码时出现 ConcurrentModificationException:

    public void refreshAvailableCaseSettings() throws Exception {
//getAvailableCases() returns reference to the instance variable
LinkedHashMap<Integer, CaseSetting> cases = getAvailableCases();
/* java.util.ConcurrentModificationException even after trying entryset()
for(Map.Entry<Integer, CaseSetting> entry : cases.entrySet()){
entry.getValue().refresh(false);
}
*/

// java.util.ConcurrentModificationException
Iterator casesIterator = cases.values().iterator();
while (casesIterator.hasNext()) {
CaseSetting caseSetting = casesIterator.next();
//refresh() updates caseSetting state by getting setting info from DB
caseSetting.refresh(false);
}
}

错误:

   java.util.ConcurrentModificationException
at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:719)
at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:752)
at java.util.LinkedHashMap$LinkedEntryIterator.next(LinkedHashMap.java:750)

我不会通过添加或删除元素来修改 map 。请帮助我理解这里的问题。

最佳答案

使用迭代器的一般约定是这样的:

当集合上的迭代器正在进行时,不得修改底层集合。

您可以对集合的元素执行任何您想要的操作,但不能触摸集合本身

您收到 ConcurrentModificationException 是因为 while 循环中的部分代码正是这样做的 - 它更改了底层集合。

标准方法是 (a) 创建集合的新副本并迭代此只读副本,或者 (b) 将更改放入单独的集合中。

关于java - LinkedHashMap -> java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61379443/

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