删除List集合中的对象问题

如果List集合存储对象,如Liser>,当需要按需求删除集合对象时,一般会想到的删除方法有,普通for循环,增强for循环,迭代器。

普通for循环:

 @Test
    public void forTest(){
       List list = new ArrayList<>();
        list.add(new User2(1,"张三1"));
        list.add(new User2(2,"张三2"));
        list.add(new User2(3,"张三3"));
        list.add(new User2(5,"张三4"));
        list.add(new User2(5,"张三5"));
        list.add(new User2(6,"张三6"));
        list.add(new User2(7,"张三7"));
        for (int i = 0; i < list.size(); i++) {
            User2 user = list.get(i);
            if(list.get(i).getId() == 5){
                list.remove(user);
            }
        }
        System.out.println(list);
    }

执行结果

[User2{id=1, name='张三1'}, User2{id=2, name='张三2'}, User2{id=3, name='张三3'}, User2{id=5, name='张三5'}, User2{id=6, name='张三6'}, User2{id=7, name='张三7'}]
 

只能删除一个id=5的数据,为什么?

因为在list删除数据后,list后面数据的下标会自动前移,而i遍历又是继续下个开始,会漏遍历相邻的数据。

增强for循环

@Test
    public void forTest(){
        List list = new ArrayList<>();
        list.add(new User2(1,"张三1"));
        list.add(new User2(2,"张三2"));
        list.add(new User2(3,"张三3"));
        list.add(new User2(5,"张三4"));
        list.add(new User2(5,"张三5"));
        list.add(new User2(6,"张三6"));
        list.add(new User2(7,"张三7"));
        for (User2 user : list) {
            if(user.getId() == 5){
                list.remove(user);
            }
        }
         System.out.println(list);
    }

 报出异常:java.util.ConcurrentModificationException,关于这个异常的原因,看了很多文章,基本上解释如下:ArrayList的父类AbstarctList中有一个域modCount,每次对集合进行修改(增添、删除元素)时modCount都会+1。
删除List集合中的对象问题_第1张图片

迭代器

 @Test
    public void forTest(){
        List list = new ArrayList<>();
        list.add(new User2(1,"张三1"));
        list.add(new User2(2,"张三2"));
        list.add(new User2(3,"张三3"));
        list.add(new User2(5,"张三4"));
        list.add(new User2(5,"张三5"));
        list.add(new User2(6,"张三6"));
        list.add(new User2(7,"张三7"));
        Iterator iterator = list.iterator();
        while (iterator.hasNext()){
            User2 user2 = (User2) iterator.next();
            if(user2.getId() == 5){
                iterator.remove();
            }
        }
        System.out.println(list);
    }

删除是成功的,推荐使用迭代器删除

你可能感兴趣的:(java基础知识,java,html,c++)