java - 迭代器是如何创建的?

标签 java collections iterator

创建 Iterator 的常用方法是:

Iterator iter = myarray.iterator(); 

谁能告诉我没有 new 操作符是如何创建 iter 的? 我知道 Iterator 是一个接口(interface),那么谁来实现它呢?

最佳答案

这是来自 ArrayList 的代码片段该部分的类(class)。如您所见,有一个内部私有(private)类实现了接口(interface)Iterator,并返回了该类的一个实例。

  766       /**
  767        * Returns an iterator over the elements in this list in proper sequence.
  768        *
  769        * <p>The returned iterator is <a href="#fail-fast"><i>fail-fast</i></a>.
  770        *
  771        * @return an iterator over the elements in this list in proper sequence
  772        */
  773       public Iterator<E> iterator() {
  774           return new Itr();
  775       }
  776   
  777       /**
  778        * An optimized version of AbstractList.Itr
  779        */
  780       private class Itr implements Iterator<E> {
  781           int cursor;       // index of next element to return
  782           int lastRet = -1; // index of last element returned; -1 if no such
  783           int expectedModCount = modCount;
  784   
  785           public boolean hasNext() {
  786               return cursor != size;
  787           }
  788   
  789           @SuppressWarnings("unchecked")
  790           public E next() {
  791               checkForComodification();
  792               int i = cursor;
  793               if (i >= size)
  794                   throw new NoSuchElementException();
  795               Object[] elementData = ArrayList.this.elementData;
  796               if (i >= elementData.length)
  797                   throw new ConcurrentModificationException();
  798               cursor = i + 1;
  799               return (E) elementData[lastRet = i];
  800           }
  801   
  802           public void remove() {
  803               if (lastRet < 0)
  804                   throw new IllegalStateException();
  805               checkForComodification();
  806   
  807               try {
  808                   ArrayList.this.remove(lastRet);
  809                   cursor = lastRet;
  810                   lastRet = -1;
  811                   expectedModCount = modCount;
  812               } catch (IndexOutOfBoundsException ex) {
  813                   throw new ConcurrentModificationException();
  814               }
  815           }
  816   
  817           final void checkForComodification() {
  818               if (modCount != expectedModCount)
  819                   throw new ConcurrentModificationException();
  820           }
  821       }

关于java - 迭代器是如何创建的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10863557/

相关文章:

java - 使用通配符迭代此通用 SET

java - Iterator 接口(interface)中的哪个方法可以移除之前返回的元素?

java - 用于从 XML 获取属性的 Xpath 不区分大小写的表达式

java - 引用 Java Enum 作为 Scala 中的类型参数

php - sql垃圾收集与清理php中的查询

java - 对 Set 的值进行排序

c++ - 使用 copy 和 back_inserter 将 vector 附加到自身时的错误结果

python - Python 中是否有可以替代 "zip"函数的函数?

java - 需要帮助找出纹理无法加载的原因

java - 如何国际化我的 eclipse Rcp 应用程序?