为什么此代码提供ConcurrentModificationException

时间:2015-07-01 16:42:59

标签: java

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ConcurrentHashMapTest {

      public static void main(String[] args) {

            Map<String, String> hMap = new HashMap<String, String>();
            hMap.put("FIRST", "1");
            hMap.put("SECOND", "2");
            hMap.put("THIRD", "3");
            hMap.put("FOURTH", "4");
            hMap.put("FIFTH", "5");
            hMap.put("SIXTH", "6");
            System.out.println("HashMap before iteration : " + hMap);
            Iterator<String> hashMapIterator = hMap.keySet().iterator();

            while (hashMapIterator.hasNext()) {
                  String key = hashMapIterator.next();
                  if (key.equals("FOURTH")){
                       hMap.put(key + "-SHIVAM", "I AM NEW KEY IN HMAP");
            }
            } 
            System.out.println("HashMap after iteration : " + hMap);
      }
}
Exception in thread "main" java.util.ConcurrentModificationException
  at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
  at java.util.HashMap$KeyIterator.next(Unknown Source)
  at ConcurrentHashMapTest.main(ConcurrentHashMapTest.java:21)

我想知道为什么会出现这种异常。在这种情况下,例外情况似乎并不公平。

2 个答案:

答案 0 :(得分:4)

在迭代它时,不允许修改集合或映射(Iterator.remove()方法除外),因为不清楚修改应该如何影响迭代。而是存储键和值以添加到单独的映射中,然后在循环后使用putAll

示例1:放置条目

Map<String, String> map = /* ... */;
Map<String, String> mapToPut = new HashMap<>();
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
  String key = iterator.next();
  if (key.equals("Test")) {
    mapToPut.put("New key for " + key, "new value");
  }
}
map.putAll(mapToPut);

示例2:删除条目

Map<String, String> map = /* ... */;
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
  String key = iterator.next();
  if (key.equals("Test")) {
    iterator.remove();
  }
}

答案 1 :(得分:1)

ConcurrentModificationException是因为您在迭代时修改集合。

你可以改变逻辑,如下所示,以避免它

   Map<String, String> hMap = new HashMap<String, String>();
                            hMap.put("FIRST", "1");
                            hMap.put("SECOND", "2");
                            hMap.put("THIRD", "3");
                            hMap.put("FOURTH", "4");
                            hMap.put("FIFTH", "5");
                            hMap.put("SIXTH", "6");
                            System.out.println("HashMap before iteration : " + hMap);
                            Iterator<String> hashMapIterator = hMap.keySet().iterator();
                            boolean isFourth =false;
                            while (hashMapIterator.hasNext()) {
                                  String key = hashMapIterator.next();
                                  if (key.equals("FOURTH")){
                                      isFourth=true; 

                            }
                            } 
                            if(isFourth)
                            hMap.put("FOURTH" + "-SHIVAM", "I AM NEW KEY IN HMAP");
                            System.out.println("HashMap after iteration : " + hMap);