簡體   English   中英

刪除ArrayList中的元素時發生ConcurrentModificationException [使用iterator.remove()]

[英]ConcurrentModificationException in removing element in ArrayList [Using iterator.remove()]

我知道我們不應該在迭代過程中修改ArrayList。

但是我正在使用Iterator遍歷列表,並使用iterator.remove()刪除元素,但仍然導致ConcurrentModification Exception。

我的程序不是多線程的。

我有很多arraylist [類包含它,並且我正在處理許多對象數組]

for(int i=0;i<obj.length;i++)
{
    if(k==i) continue;

    it = obj[i].arraylist.iterator();

    while(it.hasNext()){
    value = it.next();

      if(condn)  {
       it.remove();
       obj[k].arraylist.add(value);
       //k and i are not same 

      }

    }

}

“請注意,Iterator.remove是在迭代期間修改集合的唯一安全方法;如果在進行迭代時以其他任何方式修改基礎集合,則行為未指定。”

您可以刪除對象,但不能在迭代過程中添加新對象,這就是為什么要獲取ConcurrentModificationException的原因。

http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html

編輯:您還可以檢查:

if(k==i || obj[i].arraylist == obj[k].arraylist) continue;

您只能使用it變量在迭代過程中修改List。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM