java.util.ConcurrentModificationException: null 报错解决

标题ConcurrentModificationException

出现问题

在使用List集合的时候出现了如下报错:

在这里插入图片描述

定位代码:

在这里插入图片描述

出现原因

报错解释:“ConcurrentModificationException是基于java集合中的快速失败(fail-fast)机制产生的,在使用迭代器遍历一个集合对象时,如果遍历过程中对集合对象的内容进行了增删改,就会抛出该异常。”

当我们迭代一个ArrayList或者HashMap时,如果尝试对集合做一些修改操作(例如删除元素),可能会抛出java.util.ConcurrentModificationException的异常。

解决办法

方法一:不要在增强for循环中增删数据
方法二:使用索引(普通for循环)遍历。
方法三:使用增强for循环遍历,增删操作使用迭代器实现。

List遍历的三种方法

  1. 使用普通for
  2. 使用增强for
  3. 使用iterator

代码实现:

public static void main(String[] args) {
        List  list = new ArrayList();
 
        // 添加元素 1-10
        for (int i = 1; i < 11;i++){
            list.add(i);
        }
 
        System.out.println(list);
        System.out.println("------------------------------------");
 
 
        // List遍历的三种方式
        //1. for循环
        System.out.println("====for循环遍历");
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i)+" ");
        }
        
        //2. 增强for循环
        System.out.println( );
        System.out.println("====增强for循环遍历");
        for (Object o : list) {
            System.out.print(o+" ");
        }
        
        //3. 迭代器
        System.out.println( );
        System.out.println("====迭代器遍历");
        //根据goodsId查询产品product
        List<DealerProductEntity> productList = dealerProductService.queryListWithPro(productParams);
        Iterator<DealerGoodsEntity> iterator = goodsList.iterator();
        while (iterator.hasNext()){
            DealerGoodsEntity goodsEntity = iterator.next();
            List<DealerProductEntity> childProductList = productList.stream().filter(q -> q.getDealerGoodsId().equals(goodsEntity.getId())).collect(Collectors.toList());
            // 产品信息为空就去除查询商品,并跳过
            if (CollectionUtil.isEmpty(childProductList)){
                iterator.remove();
                continue;
            }
            goodsEntity.setProducts(childProductList);
            for (DealerProductEntity product : goodsEntity.getProducts()) {
                product.setProfitAmount(product.getNormalPrice().subtract(product.getSupplyPrice()));
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值