原文链接:
遍历删除List中符合条件的元素主要有以下几种方法:
所以推荐使用迭代器iterator,或者JDK1.8以上使用lambda表达式进行List的遍历删除元素操作。
以下是上述几种方法的具体分析:
/**
* 普通for循环遍历删除元素
*/
List students = this.getStudents();
for (int i=0; i
由于在循环中删除元素后,list的索引会自动变化,list.size()获取到的list长度也会实时更新,所以会造成漏掉被删除元素后一个索引的元素。
比如循环到第2个元素时你把它删了,接下来去访问第3个元素,实际上访问到的是原来list的第4个元素,因为原来的第3个元素变成了现在的第2个元素。这样就造成了元素的遗漏。
/**
* 增强for循环遍历删除元素
*/
List 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
*/
List students = this.getStudents();
System.out.println(students);
Iterator 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方法。
在JDK1.8中,Collection以及其子类新加入了removeIf方法,作用是按照一定规则过滤集合中的元素。
方法引用是也是JDK1.8的新特性之一。方法引用通过方法的名字来指向一个方法,使用一对冒号 :: 来完成对方法的调用,可以使语言的构造更紧凑简洁,减少冗余代码。
使用removeIf和方法引用删除List中符合条件的元素:
List urls = this.getUrls();
// 使用方法引用删除urls中值为"null"的元素
urls.removeIf("null"::equals);
作为removeIf的条件,为true时就删除元素。
使用removeIf 和 方法引用,可以将原本需要七八行的代码,缩减到一行即可完成,使代码的构造更紧凑简洁,减少冗余代码。