Alei最近和迭代器較上了勁,以前自覺得深究過迭代器,不成想原來是坐井觀天,以蠡測海。上文中寫的東西哪裏算什麼深刻探究?!但亡羊補牢,猶未遲也,經我屢次試驗,終於弄懂其中某些精巧機制,閒話少說,咱們進入正題。ide
注意,以後全部的知識點都以 ArrayList 這個容器類爲例來進行詳細說明ui
在討論這個問題以前咱們得首先在乎兩個成員變量:this
一、ArrayList 類裏繼承於 AbstractList 類的成員變量 modCount:code
protected transient int modCount = 0;
二、ArrayList 類的私有內部類 Itr 裏的成員變量 expectedModCount:對象
int expectedModCount = modCount;
再看下Itr類源碼:繼承
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(); } } @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; checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }
當咱們使用 ArrayList 容器的 iterator() 方法後,在棧空間裏建立了一個此類特定的迭代器對象,同時將成員變量 modCount 的值賦予成員變量 expectedModCount。知道這個有趣的事情後能夠先打住,讓咱們再來看看 ArrayList 類 remove() 方法的源碼:ip
參數爲 int 類型的 remove():element
public E remove(int index) { rangeCheck(index); modCount++; E oldValue = elementData(index); int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work return oldValue; }
參數爲 Object 類型的 remove():rem
public boolean remove(Object o) { if (o == null) { for (int index = 0; index < size; index++) if (elementData[index] == null) { fastRemove(index); return true; } } else { for (int index = 0; index < size; index++) if (o.equals(elementData[index])) { fastRemove(index); return true; } } return false; } /* * Private remove method that skips bounds checking and does not * return the value removed. */ private void fastRemove(int index) { modCount++; int numMoved = size - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--size] = null; // clear to let GC do its work }
以 ArrayList 類裏 remove() 方法爲例來看,只要咱們調用此方法一次,那麼 modCount 便自加一次 1。因而咱們能夠理解,modCount 是一個記錄容器對象修改次數的變量,它是一個計數器。小夥伴門徹底能夠去查源碼,不單單是 remove(),凡是涉及對 ArrayList 對象的增、刪、改的任何一種方法,當咱們調用一次這類方法,那 modCount 便會自加一次 1,即,記錄一次容器對象的改變。例如,當我建立一個 ArrayList 對象 al 後,我調用 al.add() 一次,調用 al.remove() 一次,再調用 al.add() 一次後,那麼 modCount = 3,由此說明 al 被修改了3次。字符串
在沒有建立迭代器對象以前的任何對容器對象的增刪改操做只會讓 modCount 自加,當咱們建立一個對應容器類的迭代器對象以後,int expectedModCount = modCount,迭代器對象裏的 expectedModCount 成員變量被初始化爲與 modCount 裏的數值同樣的值。
有了迭代器,而後用迭代器進行迭代,就涉及到迭代器對象的 hasNext();next()方法了,咱們看下這兩個方法的源碼:
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]; }
因而可知,兩個方法都不會改變 expectedModCount 的值,那怎麼理解 expectedModCount 這個成員變量呢?再看迭代器裏的 remove() 方法源碼:
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(); } }
在 remove() 方法的方法體裏,有「expectedModCount = modCount; 「這樣一行語句,那麼無論咱們調用多少次迭代器的 remove() 方法,始終會讓 expectedModCount 的數值等於 modCount 的值,這裏的 expectedModCount 可理解爲使用迭代器對容器類對象進行修改的」指望修改次數「,就是說:迭代器裏的這個」指望修改次數「必定要和已經記錄下的容器的修改次數 modCount 同樣,那麼當你經過迭代器對容器類對象遍歷並進行修改時,使用迭代器自己的 remove() 纔有意義(即讓 expectedModCount = modCount)!!而在 next() 方法體裏首行的 checkForComodification() 方法是這樣定義的:
final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }
看了源碼,咱們應該知道: checkForComodification() 的做用是檢查 expectedModCount 和 modCount 的值是否相等,若是不等,則拋出 ConcurrentModificationException 這個異常。這下顯而易見了,在咱們經過迭代器進行遍歷時,若使用非迭代器對象提供的修改容器類對象的任何方法,則 modCount 的值增大,而 expectedModCount 地值不發生改變,那麼在進入下一次循環時,next() 方法體裏首行的 checkForComodification() 方法檢查到 expectedModCount 與 modCount 不等後拋出了 ConcurrentModificationException。
那麼,在經過迭代器進行迭代時,容器對象裏的任何元素都不能經過容器類所提供的方法進行增刪改的操做麼?非也非也,Alei留下這樣一段代碼:
public static void main(String[] args) { Collection c = new ArrayList(); c.add(new String("aaa")); c.add(new String("bbb")); c.add(new String("ccc")); c.add(new String("ddd")); c.add(new String("fff")); c.add(new String("eee")); for (Object o : c) { // System.out.print(o + " "); if (o.equals("fff")) { c.remove(o); } } System.out.println(c); }
當咱們運行這段程序,你將會發現 」fff「 這個字符串對象怎麼被成功刪除了?!這也是我以前一直疑惑且略顯白癡的地方。其實,我能夠下定結論:在經過迭代器進行迭代時,容器對象裏的倒數第二個元素必定能夠過容器類所提供的 remove() 方法進行刪除操做(無論這個容器的 size 有多大)。這又是爲何呢?哈哈,對於這個問題,留待小夥伴們自行解決吧^_^!