[英]How to remove an element from set using Iterator?
我有一種情況,我正在使用迭代器遍歷集合。 現在,我想在迭代器位於第二個元素上時刪除第一個元素。 我該怎么做。 我知道Set是無序的,沒有像第一個或第二個元素一樣的東西,但是我的問題是我想刪除Iterator.next當前未返回的元素
我不想將此設置轉換為列表並使用listIterator。
我不想收集所有要在其他集合中刪除的對象,並調用全部刪除
迭代后我無法存儲並刪除
示例代碼。
Set<MyObject> mySet = new HashSet<MyObject>();
mySet.add(MyObject1);
mySet.add(MyObject2);
...
Iterator itr = mySet.iterator();
while(itr.hasNext())
{
// Now iterator is at second element and I want to remove first element
}
HashSet是無序的,並且javadoc明確聲明Iterator的remove方法Removes from the underlying collection the last element returned by this iterator (optional operation).
因為HashSet包含唯一元素,所以您可以在遍歷第一個元素后使用Set.remove(Object),在thios情況下,您甚至不需要轉到第二個元素
HashSet<K> hs;// you HashSet containing unique elements
if(!hs.isEmpty())
{
hs.remove(hs.iterator().next());
}
Just remember HashSet is unordered and there is no such thing as 1st or 2nd element
或者,您應該使用LinkedHashSet
,它根據插入順序為您提供有序的Set
Set.iterator()
返回一個java.lang.Iterator
。 此迭代器僅提供刪除當前元素並向前迭代的方法。
因此,如果您不想轉換集合,則僅使用Iterator
不能刪除上一個元素。
例如,您可以做的是收集要刪除的元素,然后遍歷整個集合,然后例如使用Set.removeAll(removableCollection)
刪除收集的元素:
List<MyObject> removableList = new ArrayList<>();
MyObject previous;
Iterator<MyObject> itr = mySet.iterator();
while (itr.hasNext()) {
MyObject current = itr.next();
// If you find you want to remove the previous element:
if (someCondition)
removableList.add(previous);
previous = current;
}
mySet.removeAll(removeableList);
考慮到您所說的限制,我認為沒有解決問題的辦法。
Iterator.remove()
方法將僅刪除“當前”元素。 HashSet
中刪除。 您建議(但隨后排除)的三種方法都可以使用。 我認為第二名將是表現最好的。
另一個想法是實現一個新的基於哈希表的Set
類型,該類型具有一個帶有額外刪除操作的Iterator
。 (您可以從HashSet
等的源代碼開始,重命名該類,然后對其進行修改以執行您需要的操作。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.