Why am I not getting an error when adding a duplicate item to a set?
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.
source to share
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.
source to share