2015-06-20 40 views
-2

以下代码段,而由单个线程执行时,将引发在第4行一个​​:HashMap中的迭代器,以防止并发修改

Map<String, String> map = new HashMap<String, String>(); 
map.put("key1", "value1"); 
map.put("key2", "value2"); 
for (String key : map.keySet()) { // Here 
    map.remove(key); 
} 

我无法找到任何Map.iterator()Map.mapIterator()方法上HashMap Javadoc。 我该怎么办?

+2

你的问题看起来像[XY问题(HTTP:// meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。你想做什么?现在看起来你正在试图重新创建'map.crear()'方法,或'map.keySet()。clear()'或者甚至是'map.values()。clear();'。 – Pshemo

+0

@Pshemo有一个更复杂的场景,我更喜欢从头开始写一个[MCVE](http://stackoverflow.com/help/mcve)。 –

回答

2

正如您猜测的那样,您需要一个iterator用于在迭代过程中移除项目。用Map做到这一点的方法是迭代entrySet()(或者,在keySet(),如果你只需要评估的关键):

Iterator<Map.Entry<String, String>> entryIter = map.entrySet().iterator(); 
while (iter.hasNext()) { 
    Map.Entry<String, String> entry = iter.next(); 
    iter.remove(); // Probably guard this by some condition? 
}