如何正确遍历删除List中的元素

 原文链接:



如何正确遍历删除List中的元素(普通for循环、增强for循环、迭代器iterator、removeIf+方法引用) - 腾讯云开发者社区-腾讯云 (tencent.com)

 

遍历删除List中符合条件的元素主要有以下几种方法:

  1. 普通for循环 2.增强for循环 foreach 3.迭代器iterator 4.removeIf 和 方法引用 (一行代码搞定) 其中使用普通for循环容易造成遗漏元素的问题,增强for循环foreach会报java.util.ConcurrentModificationException并发修改异常。

所以推荐使用迭代器iterator,或者JDK1.8以上使用lambda表达式进行List的遍历删除元素操作。

以下是上述几种方法的具体分析:

普通for循环

/** 
 * 普通for循环遍历删除元素
 */  
    List<Student> students = this.getStudents();  
    for (int i=0; i<students.size(); i++) {  
        if (students.get(i).getId()%3 == 0) {  
            Student student = students.get(i);  
            students.remove(student);  
        }  
    }

由于在循环中删除元素后,list的索引会自动变化,list.size()获取到的list长度也会实时更新,所以会造成漏掉被删除元素后一个索引的元素。

比如循环到第2个元素时你把它删了,接下来去访问第3个元素,实际上访问到的是原来list的第4个元素,因为原来的第3个元素变成了现在的第2个元素。这样就造成了元素的遗漏。

增强for循环 foreach

/**
 * 增强for循环遍历删除元素
 */
    List<Student> students = this.getStudents();  
    for (Student stu : students) {  
        if (stu.getId() == 2)   
            students.remove(stu);  
    }

使用foreach遍历循环删除符合条件的元素,不会出现普通for循环的遗漏元素问题,但是会产生java.util.ConcurrentModificationException并发修改异常的错误。

报ConcurrentModificationException错误的原因:

  先来看一下JDK源码中ArrayList的remove源码是怎么实现的:

public boolean remove(Object o) {
        if (o == null) {
            for (int index = 0; index < size; index++)
                if (elementData[index] == null) {
                    fastRemove(index);
                    return true;
                }
        } else {
            for (int index = 0; index < size; index++)
                if (o.equals(elementData[index])) {
                    fastRemove(index);
                    return true;
                }
        }
        return false;
    }

一般情况下程序的执行路径会走到else路径下最终调用fastRemove方法:

private void fastRemove(int index) {
        modCount++;
        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved);
        elementData[--size] = null; // clear to let GC do its work
    }

在fastRemove方法中,可以看到第2行把modCount变量的值加一,但在ArrayList返回的迭代器会做迭代器内部的修改次数检查:

final void checkForComodification() {
         if (modCount != expectedModCount)
             throw new ConcurrentModificationException();
     }

而foreach写法是对实际的Iterable、hasNext、next方法的简写,因为上面的remove(Object)方法修改了modCount的值,所以才会报出并发修改异常。

要避免这种情况的出现则在使用迭代器迭代时(显式或for-each的隐式)不要使用List的remove,改为用Iterator的remove即可。

迭代器iterator

/**
 *  迭代器iterator
 */
     List<Student> students = this.getStudents();  
     System.out.println(students);  
     Iterator<Student> iterator = students.iterator();  
     while (iterator .hasNext()) {  
         Student student = iterator .next();  
         if (iterator.getId() % 2 == 0)  
             iterator.remove();//这里要使用Iterator的remove方法移除当前对象,如果使用List的remove方法,则同样会出现ConcurrentModificationException  
     }

由上述foreach报错的原因,注意要使用迭代器的remove方法,而不是List的remove方法。

removeIf 和 方法引用

在JDK1.8中,Collection以及其子类新加入了removeIf方法,作用是按照一定规则过滤集合中的元素。

方法引用是也是JDK1.8的新特性之一。方法引用通过方法的名字来指向一个方法,使用一对冒号 :: 来完成对方法的调用,可以使语言的构造更紧凑简洁,减少冗余代码。

使用removeIf和方法引用删除List中符合条件的元素:

List<String> urls = this.getUrls();  

// 使用方法引用删除urls中值为"null"的元素
urls.removeIf("null"::equals);

作为removeIf的条件,为true时就删除元素。

使用removeIf 和 方法引用,可以将原本需要七八行的代码,缩减到一行即可完成,使代码的构造更紧凑简洁,减少冗余代码。

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值