ArrayList为什么要自己实现迭代器

ArrayList尽管继承自AbstractList,但仍需自实现Iterator接口以实现Fail-Fast机制。该机制通过modCount和expectedModCount确保在迭代过程中数组结构不变,若发生改变则抛出异常。Fail-Fast不是解决多线程安全性问题,而是防止单线程环境下在foreach操作中误用add()或remove()。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ArrayList的父类AbstractList已经实现了Iterator接口,为什么ArrayList还要自己实现Iterator接口呢?

ArrayList实现Iterator,是为了避免ArrayList在迭代过程中数组结构发生变化的而产生的问题,这个处理机制称为Fail-Fast机制,实际是一个乐观锁,实现如下。

ArrayList有一个modCount属性,在add(),remove()执行开始,modCount++。ArrayList创建迭代器对象时,会复制当前modCount到expectedModCount,迭代器每次执行next(),remove(),forEachRemaining()时,都判断modCount是否与expectedModCount相同,若不相同,则抛出异常。

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

        public E next() {
            checkForComodification();
            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];
        }

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

ArrayList不是线程安全的,Fail-Fast不是来解决多线程的问题的。这个的实际意义在于单线程时,新手在foreach中做add(),remove()操作。如果要解决多线程,要在add()和remove()中加上modCount的效验了。

百度知道有个相似的问题,是我回答的,答案差不多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值