JDK源码阅读——ArrayList(2)
来源:互联网 发布:放置江湖轻功数据 编辑:程序博客网 时间:2024/05/21 07:13
public Iterator<E> iterator() { return new Itr();}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 boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") 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]; } 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(); }}
iterator()方法新建并返回一个ArrayList的迭代器,该迭代器是个内部类,扩展了Iterator< E >接口。迭代器分别使用两个int型变量cursor和lastRet分别指向下一个返回的元素和最近返回的元素。
迭代器中用得最多的方法是hasNext()和next()。hasNext()将cursor与ArrayList的size进行比较,若相等说明无下一个元素,则返回false,否则返回true;next()首先比较cursor与size,若cursor>=size则抛出异常,否则返回cursor所指向的元素并将cursor赋给lastRet,然后cursor++。
remove方法则删除lastRet所指向的元素,即上一个返回的元素,并将lastRet赋给cursor,同时lastRet = -1。
0 0
- JDK源码阅读——ArrayList(2)
- JDK源码阅读——ArrayList(1)
- JDK源码阅读——ArrayList\LinkedList
- JDK源码阅读——ArrayList
- jdk源码阅读——ArrayList
- JDK源码阅读-ArrayList
- JDK源码阅读之ArrayList
- [Jdk源码阅读]ArrayList实现
- jdk源码阅读一:ArrayList
- jdk源码阅读之ArrayList
- 源码阅读—List分支-ArrayList
- JDK——ArrayList源码分析
- JDK源码阅读——Collection
- JDK源码阅读——LinkedList
- JDK源码阅读——模拟HashMap
- 【JDK源码阅读3-util】Collection-List---ArrayList
- JDK源码-ArrayList源码
- JDK源码剖析与最佳实践—ArrayList
- 开启线程池 加入任务 传入参数 此任务能够在执行完成时得到返回值
- Android中的Toast重复显示的问题
- 设计模式六大原则(2):里氏替换原则
- C# 关闭程序
- 通过简单的实例对指针的理解
- JDK源码阅读——ArrayList(2)
- IntelliJ IDEA 12 创建Web项目 教程 超详细版
- 剑指offer系列之11:打印1到最大的n位数
- Java String和Date的转换
- Math取整方法
- JNI学习积累之一 ---- 常用函数大全
- Android数据库高手秘籍(二):创建表和LitePal的基本用法
- 过程神经元网络
- 三、s3c2440 裸机 系统时钟和定时器的设置