Iterator接口

Iterator接口

JDK1.8

public interface Iterator<E> {
    //判断是否还有为遍历的元素
    boolean hasNext();
    //返回下一个元素
    E next();
    //移除迭代器中的元素
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }
    //遍历每个元素执行给定操作,直至遍历完毕或者返回异常,
    default void forEachRemaining(Consumer<? super E> action) {
       Objects.requireNonNull(action);
       while (hasNext())
           action.accept(next());
    }
}
    

外部迭代器实现(取自ArrayList源码)

//获取迭代器
public Iterator<E> iterator() {
    return new Itr();
}
//具体实现
private class Itr implements Iterator<E> {
        int cursor;       // 下一个要返回元素的索引
        int lastRet = -1; // 最后一个元素的索引,没有的话返回-1
        int expectedModCount = modCount;//将modCount赋值给expectedModCount,fail-fast机制

        Itr() {}//构造方法
        //判断是否还有下一个元素
        public boolean hasNext() {
            return cursor != size;
        }
        //返回下一个元素
        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();//fail-fast机制
            int i = cursor;//定义临时的当前元素的指针i并赋值
            if (i >= size)
              throw new NoSuchElementException();//如果当前指针超出了范围则抛出没有足够元素异常
            //基于ArrayList类,直接调用相关的属性
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)//直接检查数组的长度
                throw new ConcurrentModificationException();
            cursor = i + 1;//下一个元素指针
            return (E) elementData[lastRet = i];//因为下一个元素指针+1后,i就变成上一个元素了,所以先给上一个元素赋值为i,然后返回第i个元素的值,即当前元素的值
        }

        //迭代器是根据上一个元素来删除的,先判断有没有上一个元素
        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();//fail-fast机制

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

        //本方法即实现了fail-fast机制
        //调用迭代器时创建expectedModCount--预期更改次数(默认赋值为modcount),
        //每次更改集合modCount就加一,如果有多线程修改时,二者不等就会抛出异常
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值