Where does a hashset store an object with a hashcode matching the one already in the set?

StackOverflow https://stackoverflow.com/questions/23477274

  •  15-07-2023
  •  | 
  •  

Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Yes it will, because the objects are actually not the same.

Yes it will add the new object. It will not replace since they are not equal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top