gpt4 book ai didi

java - 迭代并从 map 中删除

转载 作者:行者123 更新时间:2023-12-01 22:00:14 25 4
gpt4 key购买 nike

我在做:

for (Object key : map.keySet())
if (something)
map.remove(key);

抛出了 ConcurrentModificationException,所以我将其更改为:

for (Object key : new ArrayList<Object>(map.keySet()))
if (something)
map.remove(key);

此过程以及修改 map 的任何其他过程都位于同步块(synchronized block)中。

有更好的解决方案吗?

最佳答案

以下是在 for 循环中使用迭代器删除条目的代码示例。

Map<String, String> map = new HashMap<String, String>() {
{
put("test", "test123");
put("test2", "test456");
}
};

for(Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, String> entry = it.next();
if(entry.getKey().equals("test")) {
it.remove();
}
}

关于java - 迭代并从 map 中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58711006/

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