This is a very basic question to the group for better understanding of Hashset
behavior, when the equals()
method is not overridden.
First I have created an Employee
class and overrode its hashcode()
such that it will return int 1 every time. (to ensure collision).
Next in main method, I've created 4/5 employee objects and pushed into the hashset
. Now while I iterate over the hashset
, I can see all inserted objects there. Can anyone please explain this behavior, specially how the chaining is happening here (please remember I didn't override the equal method)?
When you don't override the equals
, the default implementation of Object.equals
is used which just checks the reference equality: two distinct objects created with separate new
calls are always different (even if their content is the same). So no wonder you see all the objects inserted. But even if you create two objects with the same content, both will be inserted as well.
Having badly distributed hashCode
only affects the performance effectively converting your map into linked list (unless keys are Comparable
and you are using Java-8: in this case it will be converted to something more similar to TreeSet
).