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

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

    1. 普通for循环
    2. 增强for循环 foreach
    3. 迭代器iterator
    4. removeIf 和 方法引用 (一行代码搞定)

    其中使用普通for循环容易造成遗漏元素的问题,增强for循环foreach会报java.util.ConcurrentModificationException并发修改异常。

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

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

    1. 普通for循环

    先看代码:

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

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

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

    2. 增强for循环 foreach

    先看代码:

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

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

    报ConcurrentModificationException错误的原因:

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

     1 public boolean remove(Object o) {
     2         if (o == null) {
     3             for (int index = 0; index < size; index++)
     4                 if (elementData[index] == null) {
     5                     fastRemove(index);
     6                     return true;
     7                 }
     8         } else {
     9             for (int index = 0; index < size; index++)
    10                 if (o.equals(elementData[index])) {
    11                     fastRemove(index);
    12                     return true;
    13                 }
    14         }
    15         return false;
    16     }

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

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

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

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

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

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

    3. 迭代器iterator

    先看代码:

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

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

    4. removeIf 和 方法引用

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

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

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

    1 List<String> urls = this.getUrls();  
    2 
    3 // // 使用方法引用删除urls中值为"null"的元素
    4 urls.removeIf("null"::equals);

    其中

     "null"::equals

    相当于

    "null".equals(urls.get(i))

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

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

  • 相关阅读:
    ASP.NET 中JSON的序列化和反序列(抄的别人的,为了自己收藏)
    Javascript DOM动态添加表格
    Jquery应用技巧
    福克斯驾驶技巧(手动挡)
    肾盂分离来判断肾积水的程度
    降低车辆使用成本——节油
    青岛手精白重磅整合、横空出世申请长期置顶
    福克斯保养注意事项及驾驶技巧
    轻度肾积水怎么办?
    新手车主看过来 保养方法开车技巧全解析(求精)
  • 原文地址:https://www.cnblogs.com/nemowang1996/p/11681860.html
Copyright © 2011-2022 走看看