foreach循环详解

最近再看《阿里巴巴 Java 开发手册》,看到”集合处理”这块,要求“不要在 foreach 循环里进行元素的 remove / add 操作。 remove 元素请使用 Iterator
方式,如果并发操作,需要对 Iterator 对象加锁”。

这里写图片描述

我根据他留下的问题演示了一下反例中的代码,结果是:当把“1”换成“2”时候,程序就抛异常了。“1”的时候没有出问题。于是研究了一番。

分析问题

首先,我们要知道,foreach它其实是迭代器Iterator的语法糖,所以,用foreach来循环集合
其实就是获取集合的迭代器然后通过迭代器的API来实现对集合的遍历的。

看一下Iterator的API,了解一下它的执行过程。

    /**
     * An optimized version of AbstractList.Itr
     */
    private class Itr implements Iterator<E> {
        // index of next element to return
        int cursor;
        // index of last element returned; -1 if no such
        int lastRet = -1; 
        int expectedModCount = modCount;

        public boolean hasNext() { //(1)
            return cursor != size;
        }

        @SuppressWarnings("unchecked")
        public E next() {   //(2)
            checkForComodification();   //(3)
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = ArrayList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size && modCount == expectedModCount) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
            checkForComodification();
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

分析反例中的foreach执行过程

注意:(1),(2),(3)分别代表上面代码行后面注释的方法。

  1. 首先方法(1)判断是否有元素可以迭代?size=2,cursor=0,所以返回true。
  2. 接着执行方法(2),这里执行主要分2步:1)保存当前指针值。然后指针cursor后移一步,此时cursor=1。2)返回保存的指证值对应的元素,即返回元素“1”。
  3. 然后进入到if判断,执行list.remove(item);
  4. 执行集合的remove方法,产生2个变化:1)集合的size变了,size=1。2)ArrayList里有个计数器modCount,表示这个集合被修改的次数。每次集合结构上的修改,都会在modCount上+1。此时modCount=3。
  5. 一个遍历完,再方法(1)判断是否迭代。此时,size=1,cursor=1。所以返回false。循环终止。

这就是反例中的代码大概的执行过程。那好,为什么把“1”换成“2”就出错,同样地,我们按上的过程去分析两次代码执行的差异。

  1. 首先方法(1)判断是否有元素可以迭代?size=2,cursor=0,所以返回true。
  2. 接着执行方法(2),这里执行主要分2步:1)保存当前指针值。然后指针cursor后移一步,此时cursor=1。2)返回保存的指证值对应的元素,即返回元素“1”。
  3. 然后进入到if判断,不走if里的代码,所以size=2;
  4. 接着方法(1)去判断。cursor=1,size=2,所以返回true。接着遍历。
  5. 执行方法(2),cursor=2,返回元素“2”。
  6. 然后进入到if判断,执行list.remove(item);
  7. 依然是2个变化:size=1,modCount=3。
  8. 再方法(1)判断是否迭代。此时,size=1,cursor=2,返回true。
  9. 重点来了: 执行方法(2),进入方法(3),此时,modCount=3,expectedModCount=2,所以抛出ConcurrentModificationException异常

这就是产生错误结果的原因了。checkForComodification()方法中做的工作就是比较expectedModCount和modCount的值是否相等,如果不相等,就认为还有其他对象正在对当前的List进行操作,那个就会抛出ConcurrentModificationException异常。

执行list.remove(item)方法,会使modCount+1,但是迭代器里的expectedModCount却没变。这就是产生异常的根本原因。所以,阿里规范中要求“remove元素请使用Iterator的remove()方法”,执行这个remove()方法,会主动同步一下expectedModCount和modCount,使其保持一致。就可以避免异常的发生。

总结

  1. 复习了一下迭代器Iterator遍历集合的过程以及底层原理实现。巩固基础知识。
  2. 最好不要在集合遍历的过程中修改集合的结构。
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值