List删除集合元素

本文探讨了如何在Java中使用`Student`类,展示了`listDelete()`和`iteratorDelete()`方法,对比了list的remove()与迭代器删除元素的区别。通过实例代码,理解了迭代器在避免列表修改错误中的作用。
摘要由CSDN通过智能技术生成
   @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Student {
        private String name;
        private String age;
    }

    public static void main(String[] args) {
        iteratorDelete();
//        listDelete();
    }

    /**
     * list.remove()删除会报错
     */
    private static void listDelete() {
        List<Student> cityList = setValue();
        System.out.println(cityList.size());
        for (Student student : cityList) {
            if(student.getAge().equals("xx")){
                cityList.remove(student);
            }
        }
        System.out.println(cityList.size());
    }


    /**
     * list删除数据使用迭代器删除
     */
    private static void iteratorDelete() {
        List<Student> cityList = setValue();
        ListIterator<Student> iterator =cityList.listIterator();
        while (iterator.hasNext()) {
            Student student = iterator.next();
            if(student.getAge().equals("xx")){
                System.out.println("删除的是集合的数据,对iterator没有影响");
                iterator.remove();
            }
            System.out.println("删除后的长度:"+cityList.size());
            int i = iterator.nextIndex();
            int previousIndex = iterator.previousIndex();
            System.out.println(student + "==" + i + "==" + previousIndex);

        }
        System.out.println(cityList.size());



    }
    private static List<Student> setValue(){
        List<Student> cityList = new ArrayList<Student>();
        cityList.add(new Student("xx", "xx"));
        cityList.add(new Student("qq", "qq"));
        cityList.add(new Student("ww", "ww"));
        cityList.add(new Student("ee", "ee"));
        cityList.add(new Student("rr", "rr"));
        cityList.add(new Student("tt", "tt"));
        return cityList;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值