本文介紹了如何避免“ConcurrentModificationException"在迭代時從`ArrayList`中刪除元素?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在嘗試從 ArrayList
中刪除一些元素,同時像這樣迭代它:
I'm trying to remove some elements from an ArrayList
while iterating it like this:
for (String str : myArrayList) {
if (someCondition) {
myArrayList.remove(str);
}
}
當然,在迭代 myArrayList
的同時嘗試從列表中刪除項目時,我得到了 ConcurrentModificationException
.有沒有一些簡單的方法可以解決這個問題?
Of course, I get a ConcurrentModificationException
when trying to remove items from the list at the same time when iterating myArrayList
. Is there some simple solution to solve this problem?
推薦答案
使用 Iterator
并調用 remove()
:
Iterator<String> iter = myArrayList.iterator();
while (iter.hasNext()) {
String str = iter.next();
if (someCondition)
iter.remove();
}
這篇關于如何避免“ConcurrentModificationException"在迭代時從`ArrayList`中刪除元素?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯(lián)網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯(lián)系我們刪除處理,感謝您的支持!