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);
    
    
        }
  • 相关阅读:
    阅读笔记--- 04
    站立会议--06个人进度
    站立会议--05 个人
    站立会议---04个人
    场景分析
    站立会议---03个人
    站立会议---02 个人进度
    计算某一天距离今天多少天,多少小时,多少分钟
    改变图片颜色
    手动调整导航控制器中的viewcontroller
  • 原文地址:https://www.cnblogs.com/ooo0/p/11937484.html
Copyright © 2011-2022 走看看