创建 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/