Why do two different HashSets with the same data have the same
HashCode?
Actually this is needed to fulfill another need that is specified in Java.
The equals
method of Set
is overridden to take in consideration that equals
returns true (example a.equals(b)
) if:
a
is of type Set
and b
is of type Set
.
- both
a
and b
have exactly the same size.
a
contains all elements of b
.
b
contains all elements of a
.
Since the default equals
(which compares only the memory reference to be the same) is overridden for Set
, according to java guidelines the hashCode
method has to be overridden as well. So, this custom implementation of hashCode
is provided in order to match with the custom implementation of equals
.
In order to see why it is necessary to override hashCode
method when the equals
method is overridden, you can take a look at this previous answer of mine.
Why do 2 hashsets share the same hashcode if they are different
objects
Because as explained above this is needed so that Set
can have the custom functionality for equals
that it currently has.
If you want to just check if a
and b
are different instances of set you can still check this with operators ==
and !=
.
a == b
-> true means a
and b
point to the same instance of Set in memory
a != b
-> true means a
and b
point to different instances of Set in memory