What do you know about equals() and hashCode() methods?

Inevitable, during a Java interview you will be asked about equals() and hashCode() methods which are declared in the java.lang.Object class.

equals() method

The equals method is declared as

and indicates wether two objects are equals or not. It returns true in case the two objects are equals, and false otherwise.

hashCode() method

The hashCode() method returns a hash code value for the object and it is declared as

During the interview you can point that hasCode() method is declared using the native keyword which is used to declare methods that are implemented in platform-dependent code.

The purpose of the hashCode() method is to make the developer’s class to work properly with hash-based collections and algorithms that rely on hash codes.

All hashCode implementations must stick to a simple contract:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode() method must consistently return the same integer;
  • If two objects are equal according to the equals() 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 equals() method, then calling the has method on each of the two objects must produce distinct integer results.

The above is just a summary of the hashCode() method contract, which is fully explained in the hashCode() method’s java documentation.

Some more things you should know about the hashCode method

  • Each time you implement equals() method, you must implement hashCode() too
  • hashCode() method does not guarantee the same result in different executions

 

Spread the love

Leave a Reply