并发修改异常 java.util.ConcurrentModificationException

并发修改异常 java.util.ConcurrentModificationException

问题:
在这里插入图片描述
代码:

//使用该List集合会出现 java.util.ConcurrentModificationException
//List<Map<String,Object>> stuList = new ArrayList<>();
CopyOnWriteArrayList<Map<String,Object>> stuList = new CopyOnWriteArrayList<>();
{
    Map<String,Object> map1 = new HashMap<>();
    Map<String,Object> map2 = new HashMap<>();
    Map<String,Object> map3 = new HashMap<>();
    stuList.add(map1);
    stuList.add(map2);
    stuList.add(map3);
    map1.put("name","小刘");
    map2.put("name","小王");
    map3.put("name","小李");
}

@Test
public void test(){
    stuList.forEach(item ->{
        String name = item.get("name").toString();
        System.out.println(name);
        if("小王".equals(name)){
            Map<String,Object> map4 = new HashMap<>();
            stuList.add(map4);
            map4.put("name","小郎");
        }
    });

    System.out.println(stuList);
}

@Test
public void test1(){
    ConcurrentMap<String,Object> map = new ConcurrentHashMap<>();
    //使用该Map集合会出现 java.util.ConcurrentModificationException
    //Map<String,Object> map = new HashMap<>();
    map.put("name","A");
    map.put("age","B");
    map.put("status","C");

    for (Map.Entry<String, Object> entry : map.entrySet()) {
        String key = entry.getKey();
        String value = (String)entry.getValue();
        System.out.println("key:" + key + ",value:" + value);
        if("B".equals(value)){
            map.put("other","D");
        }
    }

    System.out.println(map);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值