簡體   English   中英

在遍歷元素時刪除元素。 removeIf 導致 ConcurrentModificationException

[英]Removing element while iterating through it. removeIf result in ConcurrentModificationException

我試圖在循環時從集合 (someObjectSet) 中刪除元素。 正如我用谷歌搜索的那樣,在這種情況下使用 removeIf 應該避免 ConcurrentModificationException 。 然而這對我不起作用。

谷歌是否對我撒了謊(或者我誤解了它),或者我沒有正確使用 removeIf ?

Set<SomeObject> someObjectSet = new HashSet<>();
someObjectSet.add(obj1);
someObjectSet.add(obj2);
someObjectSet.add(obj3);

for (SomeObject obj : someObjectSet ){
    ...
    someObjectSet.removeIf(ele -> if ele satisfies some condition)
}


我想在循環內執行 removeif 的原因是,在每個循環中,可以確定集合的其他一些元素不再需要進入循環,因此我將其刪除,以便 for 循環將不要再撿起來。

例如,
在 loop1 中,obj1 被選中。
然后在同一個循環中,它發現不再需要處理 obj2 => 從集合中刪除 obj2。
在loop2中,拾取的是obj3而不是obj2

提前致謝!

不要使用迭代的元素進行迭代和removeIf 除了您現在遇到的問題之外,這些調用相當於為集合的每個元素遍歷整個集合(因此您在迭代時仍然從集合中刪除,這解釋了異常!)。

removeIf為您迭代,所以您只需要SomeObject的謂詞:

//no loop
someObjectSet.removeIf(ele -> if ele satisfies some condition);

where ele -> if ele satisfies some condition每個SomeObject元素將被測試的條件(通過測試的元素將被刪除)。 forEach將對someObjectSet所有元素編排測試,您不需要這樣做。


如果您有基於要刪除元素的輔助條件,那么您可以組合謂詞(使用or ),如下例所示:

Set<Integer> set = new HashSet<>(Set.of(1, 2, 3, 4, 5, 6, 7, 8, 9));

Predicate<Integer> predicate = s -> s % 2 == 0;
Predicate<Integer> predicate2 = predicate.or(s -> s % 3 == 0);
set.removeIf(predicate2);

// Test with set.removeIf(predicate);
// then with set.removeIf(predicate2);
// and compare results

暫無
暫無

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

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