List 集合 remove 对象时出现 ConcurrentModificationException

在一次做项目的过程中要遍历 list 集合,然后根据条件删除 list 集合中不需要的对象,尝试了 list.remove() 方法,根本达不到目的,最后在网上看了几个帖子后才知道,要想根据条件删除 list 集合里面的对象,一定要使用 Iterator 遍历删除

如下示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class ListDemo {
    public static void main(String[] args) {
        List<Fruit> fruitList = new ArrayList<>();
        fruitList.add(new Fruit(1, "apple", "红色", 120.00));
        fruitList.add(new Fruit(2, "orange", "黄色", 140.00));
        fruitList.add(new Fruit(3, "guava", "灰色", 160.00));
        fruitList.add(new Fruit(4, "pear", "黄色", 180.00));
        fruitList.add(new Fruit(5, "mango", "黄色", 240.00));
        fruitList.add(new Fruit(6, "watermelon", "绿色", 260.00));
 
        if (Objects.nonNull(fruitList) && !fruitList.isEmpty()) {
            for (Fruit fruit : fruitList) {
                if (Objects.equals(fruit.getColor(), "黄色")) {
                    fruitList.remove(fruit);
                }
            }
        }
    }
}

执行上面的代码时会出现如下报错

对于 List 集合来说,如果你想移除 List 集合中的元素,必须要使用 Iterator 进行迭代遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ListDemo {
    public static void main(String[] args) {
        List<Fruit> fruitList = new ArrayList<>();
        fruitList.add(new Fruit(1, "apple", "红色", 120.00));
        fruitList.add(new Fruit(2, "orange", "黄色", 140.00));
        fruitList.add(new Fruit(3, "guava", "灰色", 160.00));
        fruitList.add(new Fruit(4, "pear", "黄色", 180.00));
        fruitList.add(new Fruit(5, "mango", "黄色", 240.00));
        fruitList.add(new Fruit(6, "watermelon", "绿色", 260.00));
 
        if (Objects.nonNull(fruitList) && !fruitList.isEmpty()) {
            ListIterator<Fruit> iterator = fruitList.listIterator();
            while(iterator.hasNext()){
                // 注意,进行元素移除的时候只能出现一次 iterator.next()
                if(Objects.equals(iterator.next().getColor(),"黄色")){
                    iterator.remove();
                }
            }
        }
    }
}

  

 

posted @   变体精灵  阅读(131)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示