Iterator原理(jdk1.8)

Iterator用於遍歷集合中的元素,適用於不知道集合內部結構的情況。用戶不再與集合類交互,而是與Iterator交互,其清楚知道集合類的內部狀態,通過控制iterator達到遍歷集合的目的。

Iterator<E>接口:

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());
    }
}

如ArrayList中的私有類Itr實現Iterator<E>接口:

    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();
            }
        }
   
   //forEachRemaining方法此處略過

       final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

注意最後一個函數checkForComdification,檢測ConcurrentModificationException異常。

反向輸出也可以:

public interface ListIterator<E> extends Iterator<E> 

ListIterator接口繼承Iterator接口,實現從後往前遍歷。(注意只有List集合有)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章