簡體   English   中英

迭代此集合時如何避免ConcurrentModificationException?

[英]How to avoid ConcurrentModificationException while iterating this collection?

我需要迭代一組項目,有時同時添加到該集合。 但是,如果我在迭代時添加,那么我只是通過打破迭代循環並從頭開始重新啟動迭代來重新開始迭代。 但是這會導致ConcurrentModificationException [下面的代碼]

    List<Integer> collection = new ArrayList<>();
    for (Integer lobId: collection) {
         ..
         if (someCondition) {
             collection.add(something); 
             break; 
         }
    }

我怎么能做上面這樣的事情來避免ConcurrentModificationException

簡單地使用Array而不是ArrayList來避免這種異常是否正確? 這有什么類型的專門收藏嗎?

-

編輯:

我不想為這個arraylist創建一個新副本,因為除非完成某些要求,否則我會多次重復整個迭代過程。 每次創建一個新副本會帶來一些額外的開銷,如果可能的話,我想避免。

如果可能的話,我想在該集合中維護一個排序順序和唯一值。 有沒有可以在任何圖書館使用的東西? 否則我可以在迭代過程結束時對其進行排序並刪除重復項。 這對我也沒問題。

使用另一個集合添加,並在最后組合它們。

List<Integer> collection = new ArrayList<>();
collection.add(...)
...
List<Integer> tempCollection = new ArrayList<>();    
for (Integer lobId: collection ) {
     ..
     if (someCondition) {
         tempCollection.add(something); 
         break; 
     }
}

collection.addAll(tempCollection);

這段代碼不能導致ConcurrentModificationException,因為在你添加一個元素之后你就破壞了循環並且不再使用迭代器了

ConcurrentModificationException基本上意味着您使用一個iterator迭代一個Collection (盡管由增強的for循環隱式定義),並通過更改Collection本身來動態地使其無效。 您可以通過相同的iterator進行修改來避免這種情況:

List<Integer> collection = new ArrayList<>();
ListIterator<Integer> iter = collection.listIterator();
while (iter.hasNext()) {
     Integer currVal = iter.next();
     if (someCondition) {
         iter.add(something); // Note the addition is done on iter
         break; 
     }
}

如果我理解你正確,你想迭代列表,如果有一些條件,你想打破迭代,一個項目並開始新鮮。

在這種情況下這樣做:

   List<Integer> collection = new ArrayList<>();
   boolean flag = false;
   Integer item = 
    for (Integer lobId: collection) {
         ..
         if (someCondition) {
             flag = true;
             item = something; 
             break; 
         }
    }

   if (flag){
      collection.add(item);
   }

如果其他人要在外面循環更改列表 - 你將需要同步這些訪問 - 讀取迭代器線程安全 ,並在這里使用其他答案,如復制列表或寫入其他一些副本

不要每個使用,使用好舊

for(int i=0; i<collection.size();i++)

暫無
暫無

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

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