zoukankan      html  css  js  c++  java
  • Java码农必须掌握的循环删除List元素的正确方法!

    首先看下下面的各种删除list元素的例子

    public static void main(String[] args) {
    
        List<String> list = new ArrayList<>(Arrays.asList("a1", "ab2", "a3", "ab4", "a5", "ab6", "a7", "ab8", "a9"));
    
        /**
    
         * 报错
    
         * java.util.ConcurrentModificationException
    
         */
    
        for (String str : list) {
    
            if (str.contains("b")) {
    
                list.remove(str);
    
            }
    
        }
    
        /**
    
         * 报错:下标越界
    
         * java.lang.IndexOutOfBoundsException
    
         */
    
        int size = list.size();
    
        for (int i = 0; i < size; i++) {
    
            String str = list.get(i);
    
            if (str.contains("b")) {
    
                list.remove(i);
    
            }
    
        }
    
        /**
    
         * 正常删除,每次调用size方法,损耗性能,不推荐
    
         */
    
        for (int i = 0; i < list.size(); i++) {
    
            String str = list.get(i);
    
            if (str.contains("b")) {
    
                list.remove(i);
    
            }
    
        }
    
        /**
    
         * **正常删除,推荐使用**
    
         */
    
        for (Iterator<String> ite = list.iterator(); ite.hasNext();) {
    
            String str = ite.next();
    
            if (str.contains("b")) {
    
                ite.remove();
    
            }
    
        }
    
        /**
    
         * 报错
    
         * java.util.ConcurrentModificationException
    
         */
    
        for (Iterator<String> ite = list.iterator(); ite.hasNext();) {
    
            String str = ite.next();
    
            if (str.contains("b")) {
    
                list.remove(str);
    
            }
    
        }
    
    }
    

    报异常IndexOutOfBoundsException我们很理解,是动态删除了元素导致数组下标越界了。

    那ConcurrentModificationException呢?

    其中,for(xx in xx)是增强的for循环,即迭代器Iterator的加强实现,其内部是调用的Iterator的方法,为什么会报ConcurrentModificationException错误,我们来看下源码

    取下个元素的时候都会去判断要修改的数量和期待修改的数量是否一致,不一致则会报错,而通过迭代器本身调用remove方法则不会有这个问题,因为它删除的时候会把这两个数量同步。搞清楚它是增加的for循环就不难理解其中的奥秘了。

    推荐去我的博客阅读更多:

    1.Java JVM、集合、多线程、新特性系列教程

    2.Spring MVC、Spring Boot、Spring Cloud 系列教程

    3.Maven、Git、Eclipse、Intellij IDEA 系列工具教程

    4.Java、后端、架构、阿里巴巴等大厂最新面试题

    觉得不错,别忘了点赞+转发哦!

  • 相关阅读:
    选校总结
    位运算
    剑指
    机器学习之梯度下降法
    leetcode1348 Tweet Counts Per Frequency
    UVA10308 Roads in the North 树的最长路径
    负数的处理POJ1179Polygon
    Roadblocks
    Bus Stop
    蒜头君的城堡之旅(动态规划)
  • 原文地址:https://www.cnblogs.com/javastack/p/12801676.html
Copyright © 2011-2022 走看看