publicclassArrayListimplementsCollection{ transient Object[] elementData; privateint size; //the number of elements it contains public Iterator<E> iterator(){ 44returnnew Itr(); 4} privateclassItrimplementsIterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount;
// prevent creating a synthetic constructor Itr() {}
publicbooleanhasNext(){ return cursor != size; }
public E next(){ checkForComodification(); int i = cursor; if (i >= size) thrownew NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownew ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } } }
Client类:
1 2 3 4 5 6 7 8 9 10 11 12
publicclassClient{ publicstaticvoidmain(String[] args){ Collection<Integer> c = new ArrayList<>(); c.add(1); c.add(2); c.add(3); Iterator<Integer> it = c.iterator(); while(it.hasNext()) { System.out.print(it.next() + " "); } } }