Developer87
Developer87

Reputation: 2708

Replace "contains" with "add" in collections?

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

Answers (4)

AnkeyNigam
AnkeyNigam

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

Eran
Eran

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 Lists allow duplicates. Therefore you can't replace contains with add.

Upvotes: 3

Louis Wasserman
Louis Wasserman

Reputation: 198103

Correct, that will work just fine.

Upvotes: 0

ganeshvjy
ganeshvjy

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

Related Questions