Reputation: 639
I know that the objects with same hashcode need not be the same. My question is: If a hashset encounters an object whose hashcode matches the hashcode of an object already in the hashset, but if the objects are not equal, will the hashset add the new object to it?
Upvotes: 0
Views: 67
Reputation: 88747
HashSet
internally uses a HashMap
with the values being constants the the key being the set elements. Thus the behavior is the same: if the hashcode is equal but the objects are not, collsion handling takes place and the object is put into a linked list for the resolved bucket.
Upvotes: 2
Reputation: 533720
The hashcode doesn't need to be the same, it just has to map to the same bucket. HashSet is based on HashMap and so it's behaviour is dependant on HashMap.
Two keys/elements where equals() returns false
are not the same.
HashMap in Java <= 7 using a linked list of keys/elements for the same bucket. (Not a LinkedList as such) In Java 8 it can use a tree of keys/elements.
Upvotes: 2
Reputation: 7940
Yes it will add the new object. It will not replace since they are not equal.
Upvotes: 1