Reputation: 2708
I am using plain old HashSet
implementation in my project.
I suppose that this code
if (!collection.contains(someId)) {
collection.add(someId)
// do smth
}
can be easily replaced with the following code
if (collection.add(someId)) {
// do smth
}
WITHOUT ANY SIDE effect ? Am I right?
Upvotes: 2
Views: 66
Reputation: 2820
Big Yes.
if (collection.add(someId)) {
// do smth
}
This will work with Set
implementations with no problems as they don't allows duplicate values, but will not with List
implementations as they allow duplicate items.
Upvotes: 0
Reputation: 393831
For HashSet
(or any Set
implementation) you are correct, both snippets are equivalent.
However, this is not true for any Collection
(and since your title says Replace “contains” with “add” in collections
, I thought it was worth mentioning). For example, List
's add
always returns true
, since List
s allow duplicates. Therefore you can't replace contains
with add
.
Upvotes: 3
Reputation: 407
In the case of HashMap, it replaces the old value with the new one.
In the case of HashSet, the item isn't inserted.
Upvotes: 0