How to Override equals() in Java
-
Understanding the
equals()
Method - Method 1: Basic Override of equals()
- Method 2: Using a Composite Key
- Method 3: Implementing the Comparable Interface
- Conclusion
- FAQ

In Java, the equals()
method is a fundamental part of object comparison. By default, this method checks for reference equality, meaning it only returns true if two references point to the same object. However, in many applications, especially when dealing with custom objects, you often need to compare the contents of the objects rather than their memory addresses. This is where overriding the equals()
method becomes essential.
In this tutorial, we will explore how to effectively override the equals()
method in Java, ensuring that your custom objects can be compared meaningfully. Whether you are developing a complex application or simply want to improve your coding skills, mastering this concept is crucial for Java developers.
Understanding the equals()
Method
Before diving into how to override the equals()
method, it’s important to understand its significance. The equals()
method is defined in the Object
class and is used to compare two objects for logical equality. When you override this method, you are providing a custom implementation that defines what it means for two instances of your class to be considered equal.
When overriding, it is crucial to follow certain best practices:
- Symmetry: If
a.equals(b)
is true, thenb.equals(a)
must also be true. - Transitivity: If
a.equals(b)
is true andb.equals(c)
is true, thena.equals(c)
must also be true. - Consistency: Multiple calls to
a.equals(b)
should consistently return true or false as long as the objects are unchanged. - Null comparison: Ensure that
a.equals(null)
returns false.
Now, let’s look at how to override the equals()
method in a Java class.
Method 1: Basic Override of equals()
To start, let’s create a simple class called Person
that contains attributes such as name and age. We will override the equals()
method to compare these attributes.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age && name.equals(person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
The equals()
method begins by checking if the current instance is the same as the object passed in. If they are the same, it returns true. Next, it checks if the passed object is null or if the classes are different, returning false in either case. Finally, it casts the object to Person
and compares the name
and age
fields for equality.
Output:
true
This output indicates that two instances of Person
with the same name and age are considered equal.
By overriding the hashCode()
method, we ensure that the contract between equals()
and hashCode()
is maintained, which is particularly important when using objects in hash-based collections.
Method 2: Using a Composite Key
In more complex scenarios, you may want to create a class that uses multiple fields to determine equality. For instance, let’s enhance our Person
class to include an id
field.
public class Person {
private String name;
private int age;
private String id;
public Person(String name, int age, String id) {
this.name = name;
this.age = age;
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age && name.equals(person.name) && id.equals(person.id);
}
@Override
public int hashCode() {
return Objects.hash(name, age, id);
}
}
In this version, we have added an id
field to the Person
class. The equals()
method now checks for equality based on the name
, age
, and id
fields. This means that two Person
objects will only be considered equal if all three attributes match.
Output:
false
This output shows that even if two Person
objects have the same name and age, they will not be equal unless their id
fields also match.
By using a composite key in the equals()
method, you can ensure a more granular comparison that reflects the unique identity of each object.
Method 3: Implementing the Comparable Interface
In addition to overriding the equals()
method, you may also want to implement the Comparable
interface to allow sorting. This is particularly useful when working with collections of objects.
public class Person implements Comparable<Person> {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age && name.equals(person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public int compareTo(Person other) {
return this.age - other.age;
}
}
In this implementation, we added the Comparable
interface and implemented the compareTo()
method, allowing Person
objects to be sorted by age. The compareTo()
method returns a negative number, zero, or a positive number depending on whether the current object is less than, equal to, or greater than the specified object.
Output:
1
This output indicates that the current Person
object is older than the other
object, allowing for easy sorting of a list of Person
objects.
By combining the equals()
and compareTo()
methods, you can create a robust class that not only defines equality but also supports ordering.
Conclusion
Overriding the equals()
method in Java is an essential skill for any developer. It allows you to define how objects of your custom classes should be compared, ensuring that your applications behave as expected. By following best practices and understanding the nuances of equality, you can create reliable and maintainable code. Whether you’re working with simple objects or complex data structures, mastering the equals()
method will enhance your Java programming capabilities.
FAQ
-
What happens if I don’t override the
equals()
method?
If you don’t override theequals()
method, Java will use the default implementation, which checks for reference equality rather than logical equality. -
Is it necessary to override hashCode() when overriding equals()?
Yes, it is crucial to override hashCode() whenever you override equals() to maintain the contract between these two methods. -
Can I override equals() in an immutable class?
Yes, overriding equals() in an immutable class is common and can be very effective since the object’s state will not change after creation. -
What is the role of the instanceof operator in equals()?
The instanceof operator is used to check if the passed object is an instance of the same class before performing a cast, ensuring type safety. -
How do I test my overridden equals() method?
You can test your overridden equals() method by creating different instances of your class and checking their equality using assertions in your unit tests.