首頁 > Java > java教程 > 主體

詳解Java集合框架中迭代器Iterator的範例程式碼

黄舟
發布: 2017-03-21 10:30:13
原創
1226 人瀏覽過

這篇文章主要為大家簡單介紹了Java集合框架中迭代器Iterator的相關資料,具有一定的參考價值,有興趣的小夥伴們可以參考一下

Java裡面的陣列資料可以透過索引來獲取,那麼物件呢?也是透過索引嗎?今天我們就來分析Java集合中取得集合物件的方法迭代-Iterator。

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

一、簡介

我們常常使用 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");
  }
}
登入後複製

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

二、集合分類

2.1 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的方法,其他方法類似,只要抓住底層實作方式即可。

2.2 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;
    }
登入後複製

以上是詳解Java集合框架中迭代器Iterator的範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!