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);


    }

 

posted @ 2019-11-26 18:17  草木物语  阅读(264)  评论(0编辑  收藏  举报