13.06. Equals and hashcode methods

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 the 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 a 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 do not work correctly. It is always recommended to overwrite the hashcode() method when custom objects are compared.

Output

true

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments