Why it is Important to Override equals and hashcode method for Custom Objects?
The equals
and hashCode
methods are fundamental to object comparison and hashing in Java. When working with custom objects, it is essential to override these methods to ensure correct behavior in collections such as sets, maps, and when using object comparisons.
Checking if two Objects are Equal or not?
The equals
method is used to determine if two objects are equal based on their content rather than their memory reference. By default, the equals
method in Java compares object references, which means two distinct objects with the same content will not be considered equal.
However, overriding the equals
method allows us to define our own criteria for equality.
Consider a Person
class with attributes such as name
and age
. If we want to compare two Person
objects based on their names, we need to override the equals
method and compare the name
attribute of both objects. Otherwise, two Person
objects with the same name will be considered unequal.
public class Person {
private String name;
private int age;
// Constructor and other methods...
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(name, person.name);
}
}
Whenever we override the equals
method, we must also override the hashCode
method to maintain the contract between these two methods. The hashCode
method returns an integer value used by hashing-based data structures such as HashMap
to quickly locate objects.
The general contract states that if two objects are equal, their hash codes must also be equal.
Failure to override the
hashCode
method can lead to inconsistent behavior when objects are used in hash-based collections.
Overriding equals
and hashCode
is crucial when working with collections. Collections like HashSet
, HashMap
, or Hashtable
rely on the hashCode
method to organize and search for objects efficiently.
If we don’t override equals
and hashCode
correctly, these collections may not function as expected. Objects that should be considered equal might not be properly identified, leading to duplicates in sets or incorrect retrieval from maps.
Set<Person> personSet = new HashSet<>();
Person person1 = new Person("Aman", 20);
Person person2 = new Person("Aman", 20);
personSet.add(person1);
personSet.add(person2);
System.out.println(personSet.size()); // Output: 1
In this example, without overriding equals
and hashCode
, the set will consider person1
and person2
as distinct objects, even though their attributes are the same. As a result, the set will contain duplicate objects, violating the desired behavior.
Contract between equals and hashcode method
The equals
and hashCode
methods have contractual obligations defined in the Object
class documentation. Failing to adhere to these obligations can lead to unexpected results when using objects in various Java APIs.
The obligations of the equals
method are:
- Reflexivity: An object must be equal to itself.
- Symmetry: If object A is equal to object B, then object B must be equal to object A.
- Transitivity: If object A is equal to object B and object B is equal to
If you want to learn Core Java from the beginning and that too without any cost, do checkout below Playlists: