Blog Java Importance Of Overriding Equals And Hashcode Methods

Importance Of Overriding Equals And Hashcode Methods

In Java everything is an Object. Every class extends from class Object implicitly. The equals() and hashCode() are methods of Object class. These two methods works in conjunction with each other. The following sections explain why these methods needs to overridden and the effects of not overriding.

Override equals() method

The equals() method is used to compare two objects and returns a boolean value, which indicates whether the two compared objects are same in a meaningful way. We can also compare two objects using == (equality) operator, but this comparison results true only if both object references are referring to the same object. In other words, == operator compares object references NOT actual contents of the objects. The equals() method provides meaningful way to compare objects. We override equals() method to see whether the objects themselves are equal. In order to override equals() method in a meaningful way, for each class we implement, we must decide whether two instances of the class are equal based on some criteria (perhaps we can use attributes of the class).

Following code example describes how to override equals() method.


public class CarTest {
public static void main(String... args) {
Car firstCar = new Car("red");
Car secondCar = new Car("red");

if (firstCar.equals(secondCar)) {
System.out.println(“First car and second car are equals”);
} else {
System.out.println(“First car and second car are NOT equal”);
}
}
}

class Car {

private String color;

Car(String color) {
this.color = color;
}

public String getColor() {
return color;
}

public boolean equals(Object o) {
if ((o instanceof Car) && ((Car) o).getColor() == this.color) {
return true;
} else {
return false;
}
}

}

Output
First car and second car are equals

In the above code example, we created two Car instances with same color. The color value is passed to Car instances as constructor argument. Then we are comparing each other and printing the result in the output message.

If we see the Car class declaration, especially the part which overrides the equals() method, the equals() method takes Object as argument, so we ensured actual object is an instance of Car and then we did type cast it to Car. This is because in the main method we are passing Car instance so we know for sure that we can cast Object reference in equals() method to Car. Then we are comparing the car instance color value, if color is same we decided to return true to indicate that two cars are same. On the other hand, if color is different, we decided to return false which means car instances are not equal.

If we change the color of the either first car instance or second car instance, we get different output since the color is different so cars will not be equal.

In case we do not override equals() method in our class, we cannot use instances of our class as Keys in Hashtable or HashMap and we will not get accurate Sets since there are no duplicates. In other words, we have not indicated way to identify duplicates in equals() method. Overriding equals() method is always best practice.

Override hashCode() method

The hashCode() method returns the integer hashcode value of the object so that the object can be used in collections. Collections like HashMap or HashSet use the object’s hashcode value to determine how to store the object in the collections (we call it bucketing), also the same hashcode is used to locate the object as well. Logically we can think of hashcodes a way to store/identify objects in collections.

When identifying correct object out of the collection, the following logical actions takes place.

  1. Finding the right bucket using the hashCode()
  2. Searching the bucket for the exact object using equals()

The collections will use the hashcode value to distribute elements into different buckets, so each logical bucket can contain more than one element. Again the equals() method is used to retrieve correct element from bucket.

The hashcodes are used mainly to increase the performance of large collections. The better our hashing algorithm is, the finer performance we get while storing or retrieving elements to/from collections.

The following code example shows how to override hashCode() method.


class HashCode {

public int i;

HashCode(int i) {
this.i = i;
}

public int hashCode() {
return i*7;
}

}

As shown in the above code, the hashCode() method can contain simple implementation of hashing or complex algorithm logic which returns object’s hashcode for performance gains. To use our classes as keys in the HashMap or Hashtable it is always better to override equals() and hashCode() methods so that our collections return accurate results with optimal performance.

Spread the love

LEAVE A REPLY

Please enter your comment!
Please enter your name here