java.util.ConcurrentModificationException詳解

來源:互聯網
上載者:User
文章目錄
  • 【引言】
  • 【解惑】
【引言】

經常在迭代集合元素時,會想對集合做修改(add/remove)操作,類似下面這段代碼:

for (Iterator<Integer> it = list.iterator(); it.hasNext(); ) {    Integer val = it.next();    if (val == 5) {        list.remove(val);    }}

運行這段代碼,會拋出異常java.util.ConcurrentModificationException。

【解惑】

(以ArrayList來講解)在ArrayList中,它的修改操作(add/remove)都會對modCount這個欄位+1,modCount可以看作一個版本號碼,每次集合中的元素被修改後,都會+1(即使溢出)。接下來再看看AbsrtactList中iteraor方法

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

它返回一個內部類,這個類實現了iterator介面,代碼如下:

private class Itr implements Iterator<E> {    int cursor = 0;    int lastRet = -1;    int expectedModCount = modCount;    public boolean hasNext() {        return cursor != size();    }    public E next() {        checkForComodification();        try {            E next = get(cursor);            lastRet = cursor++;            return next;        } catch (IndexOutOfBoundsException e) {            checkForComodification();            throw new NoSuchElementException();        }    }    public void remove() {        if (lastRet == -1)            throw new IllegalStateException();        checkForComodification();        try {            AbstractList.this.remove(lastRet);            if (lastRet < cursor)                cursor--;            lastRet = -1;            // 修改expectedModCount 的值            expectedModCount = modCount;            } catch (IndexOutOfBoundsException e) {            throw new ConcurrentModificationException();        }    }    final void checkForComodification() {        if (modCount != expectedModCount)            throw new ConcurrentModificationException();    }    }

在內部類Itr中,有一個欄位expectedModCount ,初始化時等於modCount,即當我們調用list.iterator()返回迭代器時,該欄位被初始化為等於modCount。在類Itr中next/remove方法都有調用checkForComodification()方法,在該方法中檢測modCount == expectedModCount,如果不相當則拋出異常ConcurrentModificationException。

前面說過,在集合的修改操作(add/remove)中,都對modCount進行了+1。
在看看剛開始提出的那段代碼,在迭代過程中,執行list.remove(val),使得modCount+1,當下一次迴圈時,執行 it.next(),checkForComodification方法發現modCount != expectedModCount,則拋出異常。

【解決辦法】
如果想要在迭代的過程中,執行刪除元素操作怎麼辦?
再來看看內部類Itr的remove()方法,在刪除元素後,有這麼一句expectedModCount = modCount,同步修改expectedModCount 的值。所以,如果需要在使用迭代器迭代時,刪除元素,可以使用迭代器提供的remove方法。對於add操作,則在整個迭代器迭代過程中是不允許的。 其他集合(Map/Set)使用迭代器迭代也是一樣。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.