Java集合框架分析(六)-Iterator迭代器分析

本篇文章主要分析一下Java集合框架中的迭代器部分,Iterator,該源碼分析基於JDK1.8,分析工具,AndroidStudio,文章分析不足之處,還請指正!

Java裏面的數組數據可以通過索引來獲取,那麼對象呢?也是通過索引嗎?今天我們就來分析一下Java集合中獲取集合對象的方法迭代-Iterator。

簡介

我們常常使用 JDK 提供的迭代接口進行 Java 集合的迭代。

        Iterator iterator = list.iterator();
         while(iterator.hasNext()){
             String string = iterator.next();
             //do something
         }

上面便是迭代器使用的基本模板,迭代其實我們可以簡單地理解爲遍歷,是一個標準化遍歷各類容器裏面的所有對象的方法類。它總是控制 Iterator,向它發送”向前”,”向後”,”取當前元素”的命令,就可以間接遍歷整個集合。在 Java 中 Iterator 爲一個接口,它只提供了迭代了基本規則:

public interface Iterator<E> {
    //判斷容器內是否還有可供訪問的元素
    boolean hasNext();
	//返回迭代器剛越過的元素的引用,返回值是 E
    E next();
	//刪除迭代器剛越過的元素
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }
}

上面便是迭代器的基本申明,我們通過具體的集合來分析。

集合分類

ArrayList的Iterator

我們通過分析ArrayList的源碼可以知道,在 ArrayList 內部首先是定義一個內部類 Itr,該內部類實現 Iterator 接口,如下:

private class Itr implements Iterator<E> {
	//....
}

在內部類實現了Iterator接口,而ArrayList的Iterator是返回的它的內部類Itr,所以我們主要看看Itr是如何實現的。

public Iterator<E> iterator() {
       return new Itr();
   }

接下來我們分析一下它的內部類Itr的實現方式。

private class Itr implements Iterator<E> {
       
       protected int limit = ArrayList.this.size;
       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 < limit;
       }
       @SuppressWarnings("unchecked")
       public E next() {
           if (modCount != expectedModCount)
               throw new ConcurrentModificationException();
           int i = cursor;
           if (i >= limit)
               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();
           if (modCount != expectedModCount)
               throw new ConcurrentModificationException();
           try {
               ArrayList.this.remove(lastRet);
               cursor = lastRet;
               lastRet = -1;
               expectedModCount = modCount;
               limit--;
           } catch (IndexOutOfBoundsException ex) {
               throw new ConcurrentModificationException();
           }
       }
       @Override
       @SuppressWarnings("unchecked")
       public void forEachRemaining(Consumer<? super E> consumer) {
           Objects.requireNonNull(consumer);
           final int size = ArrayList.this.size;
           int i = cursor;
           if (i >= size) {
               return;
           }
           final Object[] elementData = ArrayList.this.elementData;
           if (i >= elementData.length) {
               throw new ConcurrentModificationException();
           }
           while (i != size && modCount == expectedModCount) {
               consumer.accept((E) elementData[i++]);
           }
           // update once at end of iteration to reduce heap write traffic
           cursor = i;
           lastRet = i - 1;
           if (modCount != expectedModCount)
               throw new ConcurrentModificationException();
       }
   }

首先我們來分析一下定義的變量:

	  protected int limit = ArrayList.this.size;
      int cursor;       // index of next element to return
      int lastRet = -1; // index of last element returned; -1 if no such
      int expectedModCount = modCount;

其中,limit是當前ArrayList的大小,cursor代表的是下一個元素的索引,而lastRet是上一個元素的索引,沒有的話就返回-1,expectedModCount沒什麼多大用處。我們接着分析看迭代的時候怎麼判斷有沒有後繼元素的。

public boolean hasNext() {
           return cursor < limit;
   }

很簡單,就是判斷下一個元素的索引有沒有到達數組的容量大小,達到了就沒有了,到頭了!

接着,我們在分析一下獲取當前索引的元素的方法next

public E next() {
          if (modCount != expectedModCount)
              throw new ConcurrentModificationException();
          int i = cursor;
          if (i >= limit)
              throw new NoSuchElementException();
          Object[] elementData = ArrayList.this.elementData;
          if (i >= elementData.length)
              throw new ConcurrentModificationException();
          cursor = i + 1;
          return (E) elementData[lastRet = i];
      }

在next方法中爲什麼要判斷modCount呢?即用來判斷遍歷過程中集合是否被修改過。modCount 用於記錄 ArrayList 集合的修改次數,初始化爲 0,,每當集合被修改一次(結構上面的修改,內部update不算),如 add、remove 等方法,modCount + 1,所以如果 modCount 不變,則表示集合內容沒有被修改。該機制主要是用於實現 ArrayList 集合的快速失敗機制,在 Java 的集合中,較大一部分集合是存在快速失敗機制的。所以要保證在遍歷過程中不出錯誤,我們就應該保證在遍歷過程中不會對集合產生結構上的修改(當然 remove 方法除外),出現了異常錯誤,我們就應該認真檢查程序是否出錯而不是 catch 後不做處理。上面的代碼比較簡單,就是返回索引處的數組值。

對於ArrayList的迭代方法,主要是判斷索引的值和數組的大小進行比較,看看還沒有數據可以遍歷了,然後再依次獲取數組中的值,而已,主要抓住各個集合的底層實現方式即可進行迭代。

接下來我們在分析一下HashMap的Iterator的方法,其他方法類似,只要抓住底層實現方式即可。

HashMap的Iterator

在HashMap中,也有一個類實現了Iterator接口,只不過是個抽象類,HashIterator,我們來看看它的實現方式。

private abstract class HashIterator<E> implements Iterator<E> {
       HashMapEntry<K,V> next;        // next entry to return
       int expectedModCount;   // For fast-fail
       int index;              // current slot
       HashMapEntry<K,V> current;     // current entry
       HashIterator() {
           expectedModCount = modCount;
           if (size > 0) { // advance to first entry
               HashMapEntry[] t = table;
               while (index < t.length && (next = t[index++]) == null)
                   ;
           }
       }
       public final boolean hasNext() {
           return next != null;
       }
       final Entry<K,V> nextEntry() {
           if (modCount != expectedModCount)
               throw new ConcurrentModificationException();
           HashMapEntry<K,V> e = next;
           if (e == null)
               throw new NoSuchElementException();
           if ((next = e.next) == null) {
               HashMapEntry[] t = table;
               while (index < t.length && (next = t[index++]) == null)
                   ;
           }
           current = e;
           return e;
       }
       public void remove() {
           if (current == null)
               throw new IllegalStateException();
           if (modCount != expectedModCount)
               throw new ConcurrentModificationException();
           Object k = current.key;
           current = null;
           HashMap.this.removeEntryForKey(k);
           expectedModCount = modCount;
       }
   }

同樣,它也定義了一個變量

HashMapEntry<K,V> next;        // next entry to return
      int expectedModCount;   // For fast-fail
      int index;              // current slot
      HashMapEntry<K,V> current;     // current entry

next代表下一個entry的節點,expectedModCount同樣是用於判斷修改狀態,用於集合的快速失敗機制。index代表當前索引,current當前所索引所代表的節點entry,我們來看看如何判斷是否還有下一個元素的值的。

public final boolean hasNext() {
          return next != null;
      }

很簡單就是判斷next是否爲null,爲null的話就代表沒有數據了。

接着分析獲取元素的方法

 
final Entry<K,V> nextEntry() {
          if (modCount != expectedModCount)
              throw new ConcurrentModificationException();
          HashMapEntry<K,V> e = next;
          if (e == null)
              throw new NoSuchElementException();
	// 一個Entry就是一個單向鏈表
          // 若該Entry的下一個節點不爲空,就將next指向下一個節點;
          // 否則,將next指向下一個鏈表(也是下一個Entry)的不爲null的節點。
          if ((next = e.next) == null) {
              HashMapEntry[] t = table;
              while (index < t.length && (next = t[index++]) == null)
                  ;
          }
          current = e;
          return e;
      }

以上便是一些具體集合實例的迭代方法實現原理,同理可以分析其他集合的實現方式。

關於作者

專注於 Android 開發多年,喜歡寫 blog 記錄總結學習經驗,blog 同步更新於本人的公衆號,歡迎大家關注,一起交流學習~

在這裏插入圖片描述

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