Java Map在遍歷過程當中刪除元素

map遍歷判斷篩選刪除時

  • 若是對map使用put、remove或clear方法(例如map.remove直接刪除),那麼迭代器就再也不合法(而且在其後使用該迭代器將會有ConcurrentModificationException異常被拋出).
  • 當Iterator.remove方法致使map發生變化時,他會更新cursor來同步這一變化。

參見jdk文檔描述:測試

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.ui

結論: 應該使用迭代刪除

推廣

針對其餘list等集合,遍歷過程當中的刪除操做,也須要使用迭代刪除this

測試demo

private static Map<Integer, String> map=new HashMap<Integer,String>();

public static void iterTest(){
    map.put(1,"one");
    map.put(2,"two");
    map.put(3,"three");
    map.put(4,"four");
    map.put(5,"five");
    map.put(6,"six");
    map.put(7,"seven");
    map.put(8,"eight");
    map.put(5,"five");
    map.put(9,"nine");
    map.put(10,"ten");

    Iterator<Map.Entry<Integer, String>> iter = map.entrySet().iterator();
    while(iter.hasNext()){
        Map.Entry<Integer, String> entry=iter.next();
        int key=entry.getKey();
        if(key%2==1){
            System.out.println("delete this: "+key+" = "+key);
            //map.put(key, "奇數");   //ConcurrentModificationException
            //map.remove(key);      //ConcurrentModificationException
            iter.remove();        //OK
        }
    }
    //遍歷當前的map;這種新的for循環沒法修改map內容,由於不經過迭代器。
    System.out.println("-------\n\t最終的map的元素遍歷:");
    for(Map.Entry<Integer, String> entry:map.entrySet()){
        int k=entry.getKey();
        String v=entry.getValue();
        System.out.println(k+" = "+v);
    }
}

在main方法中運行 iterTest() ,輸出結果爲:code

-------
	最終的map的元素遍歷:
2 = two
4 = four
6 = six
8 = eight
10 = ten

若將three

iter.remove();

替換成rem

map.put(key, "奇數");
或者 map.remove(key);

則會報出 ConcurrentModificationException 異常文檔

相關文章
相關標籤/搜索