星空网 > 软件开发 > Java

遍历List集合,删除符合条件的元素

List集合的遍历有三种方式:增强for循环,普通for循环,Iterator迭代器遍历

如果只是对集合进行遍历,以上三种循环都可正常遍历:

(1)增强For循环遍历List集合

List<Student> stuList = new ArrayList<Student>();for(Student stu : stuList){  System.out.println(stu.getName());}

 

(2)普通For循环遍历List集合

1 List<Student> stuList = new ArrayList<Student>();2 for(int i = 0;i<stuList.size();i++){3   System.out.println(stuList.get(i).getName());    4 }  

 

(3)迭代器遍历List集合

List<Student> stuList = new ArrayList<Student>();Iterator iterator = stuList.iterator();while(iterator.hasNext()){  System.out.println(iterator.next().getName());}

 

 

然而,如果我们要遍历List集合,并删除符合条件的多个元素,则只能使用Iterator迭代器,其他两种都会报错,看下面的例子

(1)增强For循环遍历List集合,并删除另外一个数组中name相同的元素

List<Student> stuList = new ArrayList<Student>();
String[] names = ["aaa","bbb","ccc"];//此处为举例子
for(Student stu : stuList){
  for(String name : names){
     if(stu.getName() == name){
        stuList.remove(stu);//第一次删除没有问题,当删除第二个元素的时候,会报ConCurrentModificationException异常
   }
   } }

(2)普通For循环遍历List集合,并删除另外一个数组中name相同的元素

 List<Student> stuList = new ArrayList<Student>();
String[] names = ["aaa","bbb","ccc"];//此处为举例子 for(int i = 0;i<stuList.size();i++){
   for(String name : names){
     if(stuList.get(i).getName() == name){
      stuList.remove(i);//第一次删除没有问题,当多个删除的时候,会出现跳过个别元素的情况,不能完全遍历
   }
   } }

(3)迭代器遍历List集合,并删除另外一个数组中name相同的元素

List<Student> stuList = new ArrayList<Student>();
String[] names = ["aaa","bbb","ccc"];//此处为举例子
Iterator iterator = stuList.iterator(); while(iterator.hasNext()){
  Student stu = itreator.next();
  for(String name : names){
     if(stuList.get(i).getName() == name){
      iterator.remove();//此处采用iterator本身的remove方法,可以完美解决上述问题
   }
   }}
原因:增强for循环也是利用内部的iterator来遍历集合的,Iterator工作在一个独立的线程中,iterator被创建后,会建立一个单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动时,找不到迭代对象,当iterator工作时,是不允许被迭代的对象改变的,但可以被自身改变,利用Iterator的remove方法进行删除。



原标题:遍历List集合,删除符合条件的元素

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

6月跨境营销日历出炉,开启海外订单“收割期”:https://www.ikjzd.com/articles/1664146610667679745
六月新规出台!你的订单将受这些影响:https://www.ikjzd.com/articles/1664146672881790978
HAIMA海外营销|CASPER用一张床垫做到了从五个人到80亿估值的蜕变!:https://www.ikjzd.com/articles/1664152175153717250
跨境电商出海不合规常见做法(一):https://www.ikjzd.com/articles/1664172710654844930
独立站卖家必看!一文读懂支付令牌化技术!:https://www.ikjzd.com/articles/1664186632745197569
频繁出事!货还在海上飘着,货代却已经暴雷!:https://www.ikjzd.com/articles/1664190356461481986
最新研究:亚马逊、沃尔玛、Temu和Shein卖家重合率不断攀升:https://www.kjdsnews.com/a/1836554.html
三清山好玩乜?:https://www.vstour.cn/a/365182.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流