JDK7集合框架原始碼學習-ArrayList(2)迭代器

壹頁書發表於2016-07-08
  1.     private class Itr implements Iterator<E> {
  2.         int cursor; // index of next element to return
  3.         int lastRet = -1; // index of last element returned; -1 if no such
  4.         int expectedModCount = modCount;

  5.         public boolean hasNext() {
  6.             return cursor != size;
  7.         }

  8.         @SuppressWarnings("unchecked")
  9.         public E next() {
  10.             checkForComodification();
  11.             int i = cursor;
  12.             if (i >= size)
  13.                 throw new NoSuchElementException();
  14.             Object[] elementData = ArrayList.this.elementData;
  15.             if (i >= elementData.length)
  16.                 throw new ConcurrentModificationException();
  17.             cursor = i + 1;
  18.             return (E) elementData[lastRet = i];
  19.         }

  20.         public void remove() {
  21.             if (lastRet < 0)
  22.                 throw new IllegalStateException();
  23.             checkForComodification();

  24.             try {
  25.                 ArrayList.this.remove(lastRet);
  26.                 cursor = lastRet;
  27.                 lastRet = -1;
  28.                 expectedModCount = modCount;
  29.             } catch (IndexOutOfBoundsException ex) {
  30.                 throw new ConcurrentModificationException();
  31.             }
  32.         }

  33.         final void checkForComodification() {
  34.             if (modCount != expectedModCount)
  35.                 throw new ConcurrentModificationException();
  36.         }
  37.     }

ArrayList 內部類.

modCount轉自大飛部落格:
需要注意的地方是AbstractList中的一個屬性modCount。這個屬性主要由集合的迭代器來使用,對於List來說,可以呼叫iterator()和listIterator()等方法來生成一個迭代器,這個迭代器在生成時會將List的modCount儲存起來(迭代器實現為List的內部類),在迭代過程中會去檢查當前list的modCount是否發生了變化(和自己儲存的進行比較),如果發生變化,那麼馬上丟擲java.util.ConcurrentModificationException異常,這種行為就是fail-fast.

其實modCount 就是modifyCount.作用類似於資料庫的樂觀鎖版本列.

 int cursor;  初始化值為0.感覺這塊不應該使用預設值.可讀性差些。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-2121715/,如需轉載,請註明出處,否則將追究法律責任。

相關文章