前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >如何正确遍历删除List中的元素(普通for循环、增强for循环、迭代器iterator、removeIf+方法引用)

如何正确遍历删除List中的元素(普通for循环、增强for循环、迭代器iterator、removeIf+方法引用)

作者头像
崔笑颜
发布2020-06-08 16:30:54
10.7K0
发布2020-06-08 16:30:54
举报
文章被收录于专栏:小小码农一个。

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

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

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

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

普通for循环

代码语言:javascript
复制
/** 
 * 普通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

代码语言:javascript
复制
/**
 * 增强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源码是怎么实现的:

代码语言:javascript
复制
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方法:

代码语言:javascript
复制
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返回的迭代器会做迭代器内部的修改次数检查:

代码语言:javascript
复制
final void checkForComodification() {
         if (modCount != expectedModCount)
             throw new ConcurrentModificationException();
     }

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

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

迭代器iterator

代码语言:javascript
复制
/**
 *  迭代器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中符合条件的元素:

代码语言:javascript
复制
List<String> urls = this.getUrls();  

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

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

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-10-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 普通for循环
  • 增强for循环 foreach
  • 迭代器iterator
  • removeIf 和 方法引用
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档