1. 程式人生 > >遍歷集合時出現異常:java.util.ConcurrentModificationException的處理方案

遍歷集合時出現異常:java.util.ConcurrentModificationException的處理方案

0.出現異常的原因:集合在迭代過程中對其中的元素進行修改操作。

以下是解決方法

1.java遍歷Map時,對其元素進行刪除

  1. package net.nie.test;  
  2. import java.util.HashMap;  
  3. import java.util.Iterator;  
  4. import java.util.Map;  
  5. public class HashMapTest {  
  6.    private static Map<Integer, String> map=new HashMap<Integer,String>();  
  7.    /**  1.HashMap 類對映不保證順序;某些對映可明確保證其順序: TreeMap 類
     
  8.     *   2.在遍歷Map過程中,不能用map.put(key,newVal),map.remove(key)來修改和刪除元素, 
  9.     *   會引發 併發修改異常,可以通過迭代器的remove(): 
  10.     *   從迭代器指向的 collection 中移除當前迭代元素 
  11.     *   來達到刪除訪問中的元素的目的。   
  12.     *   */   
  13.    public static void main(String[] args) {  
  14.         map.put(1,"one");  
  15.         map.put(2,"two");  
  16.         map.put(3,"three"
    );  
  17.         map.put(4,"four");  
  18.         map.put(5,"five");  
  19.         map.put(6,"six");  
  20.         map.put(7,"seven");  
  21.         map.put(8,"eight");  
  22.         map.put(5,"five");  
  23.         map.put(9,"nine");  
  24.         map.put(10,"ten");  
  25.         Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();  
  26.         while(it.hasNext()){  
  27.             Map.Entry<Integer, String> entry=it.next();  
  28.             int key=entry.getKey();  
  29.             if(key%2==1){  
  30.                 System.out.println("delete this: "+key+" = "+key);  
  31.                 //map.put(key, "奇數");   //ConcurrentModificationException  
  32.                 //map.remove(key);      //ConcurrentModificationException  
  33.                 it.remove();        //OK   
  34.             }  
  35.         }  
  36.         //遍歷當前的map;這種新的for迴圈無法修改map內容,因為不通過迭代器。  
  37.         System.out.println("-------\n\t最終的map的元素遍歷:");  
  38.         for(Map.Entry<Integer, String> entry:map.entrySet()){  
  39.             int k=entry.getKey();  
  40.             String v=entry.getValue();  
  41.             System.out.println(k+" = "+v);  
  42.         }  
  43.     }  
  44. }  

2.List對其中的元素遍歷時進行刪除操作

複製程式碼
 1     public void test3() {
 2         ArrayList<Integer> arrayList = new ArrayList<>();
 3         for (int i = 0; i < 20; i++) {
 4             arrayList.add(Integer.valueOf(i));
 5         }
 6 
 7         ListIterator<Integer> iterator = arrayList.listIterator();
 8         while (iterator.hasNext()) {
 9             Integer integer = iterator.next();
10             if (integer.intValue() == 5) {
11                 iterator.set(Integer.valueOf(6));
12                 iterator.remove();
13                 iterator.add(integer);
14             }
15         }
16     }
複製程式碼