1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 遍历List集合 删除符合条件的元素

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

时间:2020-11-02 07:32:10

相关推荐

遍历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集合

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

(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异常}}}

这种方式的问题在于,删除元素后继续循环会报错误信息ConcurrentModificationException,因为元素在使用的时候发生了并发的修改,导致异常抛出。但是删除完毕马上使用break跳出,则不会触发报错,因此,也可以用于只删除一个元素的情况,删除多个元素的时候不可用。

(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);//第一次删除没有问题,当多个删除的时候,会出现跳过个别元素的情况,不能完全遍历}} }

这种方式的问题在于,删除某个元素后,list的大小发生了变化,而你的索引也在变化,所以会导致你在遍历的时候漏掉某些元素。比如当你删除第1个元素后,继续根据索引访问第2个元素时,因为删除的关系后面的元素都往前移动了一位,所以实际访问的是第3个元素。因此,这种方式可以用在删除特定的一个元素时使用,但不适合循环删除多个元素时使用。

(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方法,可以完美解决上述问题}}}

这种方式可以正常的循环及删除。但要注意的是,使用iterator的remove方法,如果用list的remove方法同样会报上面提到的ConcurrentModificationException错误,而要用iterator.remove()方法;

总结:三种方法针对只是删除一个元素都可以使用;

如果需要循环遍历删除多个元素,需要用到iterator的迭代,并且是iterator的remove()方法;

原因:

增强for循环也是利用内部的iterator来遍历集合的,Iterator工作在一个独立的线程中,iterator被创建后,会建立一个单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,所以当索引指针往后移动时,找不到迭代对象,当iterator工作时,是不允许被迭代的对象改变的,但可以被自身改变,利用Iterator的remove方法进行删除。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。