在操作集合List时,需要删除多个满足指定条件的元素。
1.使用forEach()
int size = 10;
List<Integer> list = new ArrayList<Integer>();
//使用for循环为10个元素赋值
for(int i = 0 ; i < size ; i++)
list.add(i);
//使用forEach打印元素内容
for(Integer each : list ){
System.out.print(each+"\t");
}
//结果是0 1 2 3 4 5 6 7 8 9
使用forEach打印正常。这次使用forEach将是偶数的元素移除。
for(Integer each : list){
//位运算
if((each&1) == 0){
//使用List自带的remove方法
//结果是在remove()时抛出java.util.ConcurrentModificationException异常
list.remove(each);
}
}
经过查看资料发现forEach循环的内部使用了Iterator进行了操作。详见此处
在使用.next()方法之前都会判断size,和最初的的size是否相等,否则抛出异常。
2.使用传统for循环
for(int i = 0 ; i <list.size(); i++){
if((list.get(i)&1) == 0){
list.remove(list.get(i));
i -= 1; //在移除i位置元素时,会将后面的数据先前依次移动,应该继续判断该下标的值
}
}
结论:可以正确删除指定的元素
3.使用Iterator
Iterator<Integer> iter = list.iterator();
Integer temp ;
while(iter.hasNext()){
temp = iter.next();
if((temp&1) == 0){
//此处使用Iterator的remove()方法
iter.remove();
/*
使用list的remove依然会抛出异常java.util.ConcurrentModificationException
list.remove(temp);
*/
}
}
删除前:0 1 2 3 4 5 6 7 8 9
删除后:1 3 5 7 9
建议:在对集合类进行操作时,如果只是遍历,使用forEach会使代码更加简洁。如果在遍历过程中要进行改变size的操作或得到索引的操作建议使用传统for循环或者iterator进行操作。