Mawia
Mawia

Reputation: 4310

java.util.Collection and duplicate elements

From Java Doc,

boolean add(E e)

Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.)

It only says "Returns false if this collection does not permit duplicates". It doesn't explain whether it should ignore the element or replace it. As per this phrase "Returns true if this collection changed as a result of the call", I presume that whenever false is returned by this method, it means that the Collection is ignoring the element and no element is replaced, the collection remains as is. Is that correct?

In case of duplicate elements, what is the action performed by java.util.Collection implementing classes which does not permit duplicates? Is it always ignore, or always replace, or it depends on the implementation?

Upvotes: 0

Views: 494

Answers (4)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

Concrete implementations explain it clearly, eg HashSet.add says "If this set already contains the element, the call leaves the set unchanged and returns false"

Upvotes: 0

Andrey Chaschev
Andrey Chaschev

Reputation: 16476

The question which might not be covered by docs is 'can a collection quickly detect duplicates and store them anyway?'. The answer is yes and and an example can be a Multiset in Guava in which all duplicates are counted and Collection.add(obj) always returns true.

Upvotes: 0

josh
josh

Reputation: 407

That is correct.

Collections that do not permit duplicates would return false if you were trying to add a duplicate item. Nothing would be modified what-so-ever, it would just be ignored.

If you were writing an implementation for a set, the theory would be this:

Check to see if the set already contains it. If so, return false. Else, add element to set, return true.

Upvotes: 0

Kayaman
Kayaman

Reputation: 73528

Since it returns true when the collection is modified, returning false implies that it hasn't modified the collection, i.e. it hasn't replaced the element.

Upvotes: 5

Related Questions