Equals and hashcode methods

  • Eclipse: Oxygen
  • Java: 1.8

In this tutorial we will learn “Equals and hashcode methods”. The equals method is used to compare two objects whether they have the same characteristics. This is done by comparing two hashcodes of the object which is also explained in this tutorial. The hashcode is like an id, each element has a unique id based on their declarations hence two same datatypes having same content have the same hashcode. This way the equals to methods word.

In the following program, check out the result when “= =” (equal to equal to) and equals method is used to compare string data.

“= =” (equal to equal to) method returns boolean value after completing the operation.

Output

true

“= =” (equal to equal to) method gives incorrect result when string data created with the help of object of string class is compared.

Output

false

So when we deal with String object comparison, it is recommended to use equals() method.

Output

true

When it comes to comparing the custom objects equals() methods does not work correctly. It is always recommended to overwrite the hashcode() method when custom objects are compared.

Output

true

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu