I added the same integer twice to a Set
, but it will not give any error despite Set
s not allowing duplicates. Why is this?
Set<Integer> set = new HashSet<Integer>();
set.add(1);
set.add(1);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With