循环删除list中的元素

来源:互联网 发布:mysql分布式部署方案 编辑:程序博客网 时间:2024/06/10 00:28

在做项目中循环删除list里面符合条件的元素,本来是个非常简单的问题 于是上手就写完了,不料在测试的时候定时器却报错了,后来仔细测试发现了问题 经过整理分享给大家,希望大家也多总结归纳分享 不要眼高手低。

package prectice;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;


public class GoodsStokerChice {
private String name;
private String age;


public String getName() {
return name;
}




public void setName(String name) {
this.name = name;
}




public String getAge() {
return age;
}




public void setAge(String age) {
this.age = age;
}





@Override
public String toString() {
return "GoodsStokerChice [name=" + name + ", age=" + age + "]";
}
public static void main(String[] args) {
GoodsStokerChice gc1 = new GoodsStokerChice();
GoodsStokerChice gc2 = new GoodsStokerChice();
GoodsStokerChice gc3 = new GoodsStokerChice();
gc1.setAge("1");
gc1.setName("tom");
gc2.setAge("2");
gc2.setName("jack");
gc3.setAge("3");
gc3.setName("lily");
List<GoodsStokerChice> list = new ArrayList<GoodsStokerChice>();
list.add(gc1);
list.add(gc2);
list.add(gc3);
String[] nameList = {"tom","jack","lily"};
List<String> name = Arrays.asList(nameList);

//正确方式1:使用迭代器删除 注意的是一定要使用迭代器的remove方法
Iterator<GoodsStokerChice> iterator = list.iterator();
while(iterator.hasNext()){
GoodsStokerChice g = iterator.next();
if(name.contains(g.getName())){
iterator.remove();
}
}
//结果:[]

//正确方式2:是用逆向遍历的for循环 能避免删除元素后角标变化 引起的遍历遗漏问题
//for(int i=list.size()-1;i>=0;i--){
//if(name.contains(list.get(i).getName())){
//list.remove(i);
//}
//}
//结果:[]

//错误方式1:使用增强for循环遍历删除 会报并发错误 因为增强for循环 底层实现也是迭代器 此处使用非迭代器方法 java认为其他线程在并发修改数据
//for (GoodsStokerChice g : list) {
//if(name.contains(g.getName())){
//list.remove(g);
//}
//}
//结果:Exception in thread "main" java.util.ConcurrentModificationException
//at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
//at java.util.ArrayList$Itr.next(Unknown Source)
//at prectice.GoodsStokerChice.main(GoodsStokerChice.java:68)


//错误方式2:使用普通for循环删除 由于删除完元素后 集合的长度发生变化 这时候 会遗漏掉某些元素 得到不正确的结果
//for(int i=0;i<list.size();i++){
//if(name.contains(list.get(i).getName())){
//list.remove(i);
//}
//}
//结果:[GoodsStokerChice [name=jack, age=2]]


System.out.println(list.toString());

}


}
0 0