【发布时间】:2015-01-03 08:52:50
【问题描述】:
在哈希映射中
map = new HashMap<String,String>();
it = map.entrySet().iterator();
while (it.hasNext())
{
entry = it.next();
it.remove(); //safely remove a entry
entry.setValue("new value"); //safely update current value
//how to put new entry set inside this map
//map.put(s1,s2); it throws a concurrent access exception
}
当我尝试向映射添加新条目时,它会抛出 ConcurrentModificationException。对于删除和更新迭代器具有安全删除方法。如何在迭代时添加新条目?
【问题讨论】:
-
创建一个新的
Map<String, String> foo实例并在那里设置所需的值。在您的流程结束时,使用map = foo;将此地图分配给您的旧地图。 -
我想到了。没有其他直接的方法吧?
-
您可以使用
ConcurrentHashMap来做到这一点,但这似乎有点矫枉过正。此外,这些清理任务不适合使用迭代器。
标签: java iterator concurrentmodification