![](/img/trans.png)
[英]Multiple threads using iterator.remove() on a single collection returning fail-fast iterator
[英]Collection - Iterator.remove() vs Collection.remove()
按照Sun,
“Iterator.remove是在迭代期間修改集合的唯一安全方法;如果在迭代進行過程中以任何其他方式修改基礎集合,則行為未指定。”
我有兩個問題:
首先, Collection.remove()
非常有用。 它適用於很多用例,可能比Iterator.remove()
。
但是,后者解決了一個特定問題:它允許您在迭代時修改集合。
Iterator.remove()
解決的問題如下所示:
List<Integer> l = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4));
for (int el : l) {
if (el < 3) {
l.remove(el);
}
}
此代碼無效,因為l.remove()
在迭代過程中調用l
。
以下是編寫它的正確方法:
Iterator<Integer> it = l.iterator();
while (it.hasNext()) {
int el = it.next();
if (el < 3) {
it.remove();
}
}
正如您引用的文檔明確指出的那樣,
Iterator.remove是在迭代期間修改集合的唯一安全方法
(重點補充)
使用am迭代器時,除了調用Iterator.remove()
之外,不能修改集合。
如果您沒有迭代集合,則可以使用Collection.remove()
。
如果您正在迭代集合並使用:
Collection.remove()
您可以獲得運行時錯誤(特別是ConcurrentModifcationException),因為您正在更改先前使用的對象的狀態,以構造完成循環所需的顯式系列調用。
如果您使用:
Iterator.remove()
您告訴運行時您想要更改基礎集合並重新評估完成循環所需的顯式調用系列。
是什么讓這個操作“Iterator.remove()”比其他操作穩定?
這意味着迭代器知道您刪除了元素,因此它不會產生ConcurrentModifcationException。
如果它在大多數用例中沒用,它們為什么提供“Collection.remove()”方法呢?
通常你會使用Map.remove()或Collection.remove(),因為這比迭代每個對象更有效。 如果你經常迭代刪除我懷疑你應該使用不同的集合。
只是一個設計選擇。 可以指定不同的行為(即迭代器必須跳過由Collection.remove()刪除的值),但這會使集合框架的實現變得更加復雜。 因此選擇不加以指定。
這非常有用。 如果您知道要刪除的對象,為什么要迭代?
據我所知,Collection.remove(int index)也將返回被刪除的對象。 Iterative.remove()不會。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.