在java的集合中,List接口繼承Collection接口,AbstractList類實現(xiàn)了List接口,在AbstractList中的內(nèi)部類Itr實現(xiàn)了Iterator接口 ArrayList實現(xiàn)List接口并繼承AbstractList類,結(jié)構(gòu)圖如下:(圖片出自網(wǎng)絡(luò)) Iterator接口源碼: 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()); } }
private class Itr implements Iterator<E> { /**元素的下標(biāo) * Index of element to be returned by subsequent call to next. */ int cursor = 0; /**上一個元素的下標(biāo)。如果元素已被刪除就設(shè)置為-1 * Index of element returned by most recent call to next or * previous. Reset to -1 if this element is deleted by a call * to remove. */ int lastRet = -1; /**允許修改的次數(shù),違規(guī)操作會拋異常 * The modCount value that the iterator believes that the backing * List should have. If this expectation is violated, the iterator * has detected concurrent modification. */ int expectedModCount = modCount; /*檢查是否還有下一個元素*/ public boolean hasNext() { return cursor != size(); } /*光標(biāo)下移,并且返回當(dāng)前的元素*/ public E next() { checkForComodification(); try { int i = cursor; E next = get(i); lastRet = i; cursor = i + 1; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } /*移除元素*/ public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { AbstractList.this.remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } ArrayList中的iterator()方法: public Iterator<E> iterator() { return new Itr(); } ArrayList中的內(nèi)部類Itr源碼功能類似于AbstractList的內(nèi)部類Itr。 閱讀了Iterator的源碼,再回頭看Iterator遍歷List的過程,理解就會深刻很多。 List<String> list=new ArrayList<String>();
list.add("apple"); list.add("banana"); list.add("watermelon");
for (Iterator<String> iterator=list.iterator();iterator.hasNext();) {
System.out.println( iterator.next()); |
|
來自: 一本正經(jīng)地胡鬧 > 《待分類》