zoukankan      html  css  js  c++  java
  • java 迭代的陷阱

        /**
         * 关于迭代器,有一种常见的误用,就是在迭代的中间调用容器的删除方法。
         * 但运行时会抛出异常:java.util.ConcurrentModificationException
         *
         * 发生了并发修改异常,为什么呢?因为迭代器内部会维护一些索引位置相关的数据,要求在迭代过程中,容器不能发生结构性变化,否则这些索引位置就失效了。
         * 所谓结构性变化就是添加、插入和删除元素,只是修改元素内容不算结构性变化。
         *
         * @param list
         */
        public void remove(ArrayList<Integer> list) {
            for (Integer a : list) {
                if (a <= 100) {
                    list.remove(a);
                }
            }
        }
    /**
         * 如何避免异常呢?可以使用迭代器的remove方法
         *
         * @param list
         */
        public static void remove2(ArrayList<Integer> list) {
            Iterator<Integer> it = list.iterator();
            while (it.hasNext()) {
                if (it.next() <= 100) {
                    it.remove();
                }
            }
        }
    public static void main(String[] args) {
    
            ArrayList<Integer> intList = new ArrayList<Integer>();
            intList.add(11);
            intList.add(456);
            intList.add(789);
    
            Test test = new Test();
            // test.remove(intList);
            test.remove2(intList);
    
    
        }
  • 相关阅读:
    系统幂等设计
    一文读懂消息队列一些设计
    DDD应对运营活动系统腐化实践
    一文读懂DDD
    阿里是如何处理分布式事务的
    核心交易系统架构演进
    系统服务化
    重构系统的套路-写有组织的代码
    数组生成树形结构
    js 对象全等判断
  • 原文地址:https://www.cnblogs.com/ooo0/p/11937484.html
Copyright © 2011-2022 走看看