标题ConcurrentModificationException
出现问题
在使用List集合的时候出现了如下报错:
定位代码:
出现原因
报错解释:“ConcurrentModificationException是基于java集合中的快速失败(fail-fast)机制产生的,在使用迭代器遍历一个集合对象时,如果遍历过程中对集合对象的内容进行了增删改,就会抛出该异常。”
当我们迭代一个ArrayList或者HashMap时,如果尝试对集合做一些修改操作(例如删除元素),可能会抛出java.util.ConcurrentModificationException的异常。
解决办法
方法一:不要在增强for循环中增删数据
方法二:使用索引(普通for循环)遍历。
方法三:使用增强for循环遍历,增删操作使用迭代器实现。
List遍历的三种方法
- 使用普通for
- 使用增强for
- 使用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()));
}
}
}