Reputation: 877
could you help me understand this snippet? I don't understand why this function have to check the collection contains the element before remove it. Since the iterator is from the collection, all element returned by iterator is definitely in collection.So I think it's a waste of time. Thank you a lot
public boolean removeAll(Collection<?> c) {
Objects.requireNonNull(c);
boolean modified = false;
Iterator<?> it = iterator();
while (it.hasNext()) {
if (c.contains(it.next())) {//I don't understand
it.remove();
modified = true;
}
}
return modified;
}
Upvotes: 0
Views: 44
Reputation: 393811
This looks like an implementation of Set
's removeAll.
The iterator
is not iterating on the Collection
passed to the method. It is iterating on the Set
on which the method was called.
set1.removeAll(collection2);
You are iterating over the elements of set1
and check for each one of them whether it belongs to collection2
before removing it from the Set
.
Upvotes: 3
Reputation: 201437
That snippet is from a class that implements Collection
. The method only removes items from the local class instance (through the local iterator()
) when the Collection
c
also contains an item that is equals
.
Upvotes: 0