Reputation: 9048
Are there any real world examples of when a caller might use the value returned from Collection.remove()
?
I'm happy that the method returns a boolean but am struggling to think of a case when the result would be useful to a caller.
Upvotes: 3
Views: 2231
Reputation: 51383
As the javadoc says
Removes a single instance of the specified element from this collection, if it is present (optional operation).
The collection might contain multiple objects that are all equal, because a collection is not necessarily a Set.
So one use case might be to remove all instances of an object equal to the remove argument.
while(col.remove(anObject));
Remember that the javadoc also says:
More formally, removes an element e such that (o==null ? e==null : o.equals(e))
So if you get a collection that might contain null values and you only want to process the "real" objects, you can make this code easier
for(Object obj : col) {
if(obj != null){
doSomethingWithObject(obj);
}
}
by removing the null
values first:
while(col.remove(null));
for(Object obj : col) {
doSomethingWithObject(obj);
}
Upvotes: 4
Reputation: 425073
Collection.remove()
returns false
when the object passed to it was not found in the collection.
That sounds fairly useful to me, especially if you expected the object to be there - once removed it would be impossible to confirm that it previously was. The call to remove()
is the last chance to discover it wasn't there.
Upvotes: 6