What is the significance of equals method in java?

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP and OCPWCD certified and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

In this article we are going to learn about object equality and hashcode and how are the related with each other. Java uses equals method object equality.

Object equality:

Let us say we have a class called Bike of which objects we are going to make and it has two properties i.e. engine capacity and color of the bike

We have provided the toString() method implementation to have meaningful representation of our bike object .Here is another class in which we will create the objects of Bike

Now we have created two Bike objects and all the parameters are the same, i.e. engine capacity for them is 150 cc and the color is red. For us now they are equal bikes, so let us run this program and we are expecting the output as “true” . The output is

Now why is that? Both bikes have the same exact parameters so why aren’t they equal? We know that but does the program know how to check whether bikes are equal or not? Not yet. We need to tell exactly what being equal means. Here comes the concept of equals method. So let write  equals method for Bike class and the bike class becomes

The equals method will compare whether the bikes have the same color and engine capacity and then return true if they are equal otherwise return false.

Now run the program again and check output, this time it prints

Remember that equals is object class method and its signature is

A contract for equals method needs to be followed if we really want to make it useful

  • For any reference variable one, one.equals(one)  must return true .
  • For any reference variables one and two, one.equals(two) should return true if and only if two.equals(one) returns true .
  • For any reference variables one, two and three , if one.equals(two) == true and two.equals(three) == true then one.equals(three) must be true
  • For any reference variables one and two ,if one.equals(two) returns true then it should return the same even if they are compared a multiple number of times. i.e. Two object comparisons should always result in the same return value.Hope this articles helps understand the equals method.

 

 

Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *