What I know is:-
"int hashCode()
returns the memory address of the object as
the default hash value of the object."
If the references x
and y
denote two different objects, the expression
(x.hashCode() == y.hashCode())
is not always false
So, I want to ask in which cases the hash values of 2 different objects are same.
You can override hashCode
in your classes. You would usually override it along with overriding equals
, so that if a.equals(b)
is true, a.hashCode() == b.hashCode()
is also true (even if (a == b)
is false).
However, even if a.equals(b)
is false, a.hashCode() == b.hashCode()
may still be true.
As you can see in the Javadoc of Object class :
- If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
- It is not required that if two objects are unequal according to the java.lang.Object.equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With