Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Under what Conditions two different objects may have same hashcode() value..?

Tags:

java

hashcode

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.

like image 584
Sukhbir Avatar asked Mar 15 '23 13:03

Sukhbir


1 Answers

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.
like image 88
Eran Avatar answered Apr 07 '23 10:04

Eran