记录遍历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<Integer, String> map=new HashMap<Integer,String>();  
      
   /**  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<Map.Entry<Integer, String>> it = map.entrySet().iterator();  
        while(it.hasNext()){  
            Map.Entry<Integer, String> 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<Integer, String> 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
`java.util.ConcurrentModificationException`异常通常发生在多线程环境下,当程序试图同修改一个集合(如List、Set或Map)的内容,而这些集合是被其他线程正在遍历候。这是因为Java的集合类内部维护了一个迭代器,这个迭代器假设集合的内容不会改变,但在并发情况下,如果线程A正在遍历,线程B修改了集合,就会导致迭代器无法正确跟踪元素,从而抛出此异常。 要解决这个问题,可以采取以下几种策略: 1. **避免在迭代过程中修改集合**:如果你知道可能会有修改,尽量在遍历之前完成所有可能的修改操作,或者使用不可变集合(如`Collections.unmodifiableList()`)。 2. **同步操作**:如果必须在迭代过程中修改,确保对集合的修改操作是在同步块中进行,这样可以保证同一间只有一个线程可以修改集合。 3. **使用并发集合**:Java提供了一些并发版本的集合,如`CopyOnWriteArrayList`和`ConcurrentHashMap`,它们在修改会创建新的视图,避免了直接抛出异常,而是返回一个新的结果。 4. **使用`Iterator.remove()`替换`List.remove()`**:在`List`迭代器上调用`remove()`方法,不会抛出`ConcurrentModificationException`,但会导致迭代提前结束。 在你给出的代码示例中,删除元素引发异常是因为尝试在线程安全的迭代中修改了集合结构。正确的做法是先移除元素再迭代,或者在遍历使用`Iterator.remove()`替换`List.remove()`。 ```java // 错误示例 List<Integer> list = ...; Iterator<Integer> it = list.iterator(); while (it.hasNext()) { if (it.next().equals(3)) { // 不应在迭代过程中修改 it.remove(); // 这里会抛出异常 } } // 正确示例 List<Integer> list = ...; Integer target = 3; list.remove(target); // 先移除元素 for (Integer element : list) { // 现在可以安全地遍历 } ``` [^1]: java.util.ConcurrentModificationException异常原因及解决方法。@TOC 欢迎使用Markdown编辑器 : java.util.ConcurrentModificationException异常原因及解决方法。复制代码 上述代码在删除value=3的元素,报java.util.ConcurrentModificationException异常,如下图。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值