ArrayList的Iterator迭代器

下图是迭代器的源码,对应都有注释

主要关注hasNext、next、remove这三个方法

其中next2方法是对next的方法改造,功能一致

同理,remove2方法是对remove的方法改造,功能一致

    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;

        Itr() {}
		//咱们创建迭代器实例后,cursor默认为0
        //首先第一步如果ArrayList中有元素,那么该方法则返回true
        public boolean hasNext() {
            return cursor != size;
        }
		//接下来看next方法,抛异常的暂时不管
        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            //步骤一:先把cursor赋值给i
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            //获取到ArrayList底层的数组
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            //步骤二:让cursor又等于i+1,实际咱们刚刚令i=cursor
            cursor = i + 1;
            //这个时候先把i赋值给lastRet,再获取的元素elementData[i]
            //这个i实际上是刚进入方法的步骤一
            return (E) elementData[lastRet = i];
        }
        
         public E next2() {
            Object[] elementData = ArrayList.this.elementData;
            return (E) elementData[lastRet = cursor++];
        }

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

            try {
                //移除元素是调用ArrayList的remove方法
                //底层是通过index来移除,例:移除index=3(注:index是从0开始),则把index从4到最后重新拷贝到index=3的位置
                ArrayList.this.remove(lastRet);
                //在hasNext方法中lastRet是等于i的,cursor是比i大1
                //在这一步,相当于让cursor-1
                cursor = lastRet;
                //把lastRet重置为-1,可以防止重复调用2次remove
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
        
        public void remove2() {
            try {
                ArrayList.this.remove(lastRet);
                cursor--;
                lastRet = -1;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }

欢迎各位同学一起交流,有不对的地方欢迎指出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值