记录遍历map和list时出现的异常java.util.ConcurrentModificationException异常

记录遍历map和list时出现的异常java.util.ConcurrentModificationException异常

主要原因是对其中的一些值进行了修改或者删除!
解决方案:
1.java遍历Map时,对其元素进行删除

package net.nie.test;  
  
import java.util.HashMap;  
import java.util.Iterator;  
import java.util.Map;  
  
public class HashMapTest {  
   private static Map map=new HashMap();  
      
   /**  1.HashMap 类映射不保证顺序;某些映射可明确保证其顺序: TreeMap 类 
    *   2.在遍历Map过程中,不能用map.put(key,newVal),map.remove(key)来修改和删除元素, 
    *   会引发 并发修改异常,可以通过迭代器的remove(): 
    *   从迭代器指向的 collection 中移除当前迭代元素 
    *   来达到删除访问中的元素的目的。   
    *   */   
   public static void main(String[] args) {  
        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> it = map.entrySet().iterator();  
        while(it.hasNext()){  
            Map.Entry entry=it.next();  
            int key=entry.getKey();  
            if(key%2==1){  
                System.out.println("delete this: "+key+" = "+key);  
                //map.put(key, "奇数");   //ConcurrentModificationException  
                //map.remove(key);      //ConcurrentModificationException  
                it.remove();        //OK   
            }  
        }  
        //遍历当前的map;这种新的for循环无法修改map内容,因为不通过迭代器。  
        System.out.println("-------\n\t最终的map的元素遍历:");  
        for(Map.Entry entry:map.entrySet()){  
            int k=entry.getKey();  
            String v=entry.getValue();  
            System.out.println(k+" = "+v);  
        }  
    }  
}  

2.List对其中的元素遍历时进行删除操作

复制代码

1 public void test3() {
2 ArrayList arrayList = new ArrayList<>();
3 for (int i = 0; i < 20; i++) {
4 arrayList.add(Integer.valueOf(i));
5 }
6
7 ListIterator 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 }

原文:https://blog.csdn.net/qq_40090512/article/details/79927941

你可能感兴趣的:(问题日志)