Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't I get an error when adding a duplicate item to a Set?

Tags:

java

set

I added the same integer twice to a Set, but it will not give any error despite Sets not allowing duplicates. Why is this?

 Set<Integer> set = new HashSet<Integer>();
 set.add(1);
 set.add(1);
like image 572
Sopan K Kokre Avatar asked Dec 26 '22 02:12

Sopan K Kokre


1 Answers

Set:add is not supposed to give you an error when you try to add a value already in the Set. It will just return false and not add the value to the Set.

Check the JavaDoc:

boolean add(E e)

Adds the specified element to this set if it is not already present (optional operation). More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false. In combination with the restriction on constructors, this ensures that sets never contain duplicate elements.

like image 174
Eran Avatar answered Dec 28 '22 11:12

Eran