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.
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