I have a HashSet<Obj>
containing one item. A new item trying to be added into the Set is the same as the one existing item, .equals()
. To confirm newElement
is in fact the same, I have some debug prints looping through my HashSet
and printing for each item:
does current item .equals(newElement)
.
This confirms there is a .equals()
object in the set already.
This is where the fun starts, if I call add(newElement)
I am expecting it to not add, or at least overwrite what's already in the set. The set should only have the 1 unique item after the add. In my case, it has 2!
To help figure out why add()
was working that way, I ran a Set.contains(newElement)
which should have returned true, but in my case it returns false. This is why my add()
works the way it does.
Any reason why an item in a set could be .equals(newElement)
but Set.contains(newElement)
could return false? I have checked my .equals()
and it seems to work the way I expect, printing out the objects show what .equals()
is confirming. I thought maybe something with how HashSet
handles add
and contains
but that checks (o==null ? e==null : o.equals(e))
from the Java documentation.
I am also overriding hashCode()
, the values used within I am printing as part of my debug which shows the same logical items.