gpt4 book ai didi

java - 为什么从 HashMap 中删除时会出现 ConcurentModificationException?

转载 作者:搜寻专家 更新时间:2023-11-01 03:59:41 26 4
gpt4 key购买 nike

我想通过应用条件从 HashMap 中删除一个项目。考虑这段代码:

Set<Foo> set = myMap.keySet();
Iterator<Foo> itr = set.iterator();
while (itr.hasNext())
{
Foo foo = itr.next();
if (foo.toString().length() < 3) {
myMap.remove(foo); //remove the pair if key length is less than 3
}
}

所以我得到一个 ConcurentModificationException 因为在迭代期间我正在修改 HashMap。我应该怎么办?有没有其他方法可以搜索我的条件并在最后执行删除命令,以避免出现此异常?

最佳答案

使用 itr.remove() 而不是 myMap.remove(o.toString())

关于java - 为什么从 HashMap 中删除时会出现 ConcurentModificationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4299538/

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