首頁  >  文章  >  Java  >  在迭代期間從 ArrayList 中刪除元素時如何避免 ConcurrentModificationException?

在迭代期間從 ArrayList 中刪除元素時如何避免 ConcurrentModificationException?

Barbara Streisand
Barbara Streisand原創
2024-10-28 03:18:30913瀏覽

How to Avoid ConcurrentModificationException When Removing Elements from an ArrayList During Iteration?

迭代時修改 ArrayList 時如何處理 ConcurrentModificationException

迭代 ArrayList 時,嘗試在迭代期間刪除元素可能會導致 java.util.ConcurrentModationException 。發生這種情況是由於 ArrayList 的快速失敗機制,該機制會在迭代期間檢測列表結構的任何更改,並引發異常以防止意外結果。

要解決此問題,有兩種主要方法可供考慮:

選項1:建立要刪除的值清單

此方法涉及識別循環中要刪除的元素並將它們添加到單獨的列表中。迭代完成後,使用removeAll()方法從原始清單中刪除所有元素。

<code class="java">ArrayList<A> valuesToRemove = new ArrayList<>();

for (A a : abc) {
    if (a.shouldBeRemoved()) {
        valuesToRemove.add(a);
    }
}

abc.removeAll(valuesToRemove);</code>

選項2:使用迭代器Remove

或者,您可以使用迭代器自己的刪除()方法。但是,請注意,這種方法需要使用傳統的 for 循環,而不是增強的 for 循環。

<code class="java">for (Iterator<A> iterator = abc.iterator(); iterator.hasNext();) {
    A a = iterator.next();
    if (a.shouldBeRemoved()) {
        iterator.remove();
    }
}</code>

透過實作其中一種方法,您可以避免 ConcurrentModificationException,同時在迭代期間有效修改 ArrayList。

以上是在迭代期間從 ArrayList 中刪除元素時如何避免 ConcurrentModificationException?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn