Why am I not getting an error when adding a duplicate item to a set?

I have added the same integer twice to Set

, but it won't give any error despite Set

not allowing duplicates. Why is this?

 Set<Integer> set = new HashSet<Integer>();
 set.add(1);
 set.add(1);

      

+3


source to share


3 answers


Set:add

shouldn't give you an error when trying to add a value already in Set

. It will just return false

and not add a value to Set

.

Check JavaDoc :



boolean add (E e)

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

+5


source


Set.add returns boolean. If the element is already set, false is returned.

So, if you have a choice. Or...

if (!set.add(i)) {
    // item already in set; not added
}

      



... or

if (set.contains(i)) {
    // item already in set
}

      

+1


source


Please refer to the official JAVA doc for more information on the add method: https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html#add%28E%29

It will simply return false if the Set already contains an element.

+1


source







All Articles