Table of contents
1.
Introduction
2.
equals() method
2.1.
Syntax
2.2.
Program
2.3.
Java
3.
hashCode() method
3.1.
Syntax
4.
Frequently Asked Questions
4.1.
What happens if I don't override the equals() method in my class?
4.2.
Can I override the equals() method without overriding the hashCode() method?
4.3.
What is the purpose of the hashCode() method?
5.
Conclusion
Last Updated: Jul 25, 2024
Medium

Equals and Hashcode in Java

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Java, the equals() & hashCode() methods are essential concepts that every developer should understand. These methods are used to compare objects & determine their equality. The equals() method is used to compare two objects for equality, while the hashCode() method returns a unique integer value for each object. 

Equals and Hashcode in Java

In this article, we will learn the basics of equals() & hashCode(), their syntax, and principles, with examples. 

equals() method

The equals() method is a fundamental method in Java that is used to compare two objects for equality. It is defined in the Object class, which is the parent class of all classes in Java. The equals() method takes an object as a parameter & returns a boolean value indicating whether the two objects are equal or not.

The default implementation of the equals() method in the Object class compares the memory addresses of the two objects. However, this behavior can be overridden in custom classes to provide a more meaningful comparison based on the objects' properties or attributes.

Syntax

The syntax for the equals() method is as follows:

public boolean equals(Object obj) {
    // comparison logic here
}


To override the equals() method in your custom class, you need to follow these rules:

1. The method must be declared as public.
 

2. The method must take an Object as a parameter.
 

3. The method must return a boolean value.
 

Inside the method, you write the comparison logic to determine whether the two objects are equal based on their relevant properties or attributes.

Some principles of equals() method of Object class:

When overriding the equals() method in your custom class, there are some important principles to keep in mind:

1. Reflexive: For any non-null reference value x, x.equals(x) should return true.
 

2. Symmetric: For any non-null reference values x & y, x.equals(y) should return true if & only if y.equals(x) returns true.
 

3. Transitive: For any non-null reference values x, y, & z, if x.equals(y) returns true & y.equals(z) returns true, then x.equals(z) should return true.
 

4. Consistent: Multiple invocations of x.equals(y) should consistently return true or false, provided no information used in the comparison is modified.
 

5. For any non-null reference value x, x.equals(null) should return false.

Program

Let's take a look at an example program that shows the usage of the equals() method:

  • Java

Java

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 other = (Person) obj;

       return age == other.age && Objects.equals(name, other.name);

   }

}

public class Main {

   public static void main(String[] args) {

       Person person1 = new Person("Rahul", 25);

       Person person2 = new Person("Rahul", 25);

       Person person3 = new Person("Rinki", 30);

       System.out.println(person1.equals(person2));

       System.out.println(person1.equals(person3));

   }

}
You can also try this code with Online Java Compiler
Run Code

Output

True
False

In this example, we have a `Person` class with `name` & `age` attributes. We override the `equals()` method to compare two `Person` objects based on their `name` & `age`. The `equals()` method first checks if the two objects are the same instance, then it checks if the other object is null or of a different class. Finally, it compares the `name` & `age` attributes of the two objects.

In the `Main` class, we create three `Person` objects & compare them using the `equals()` method. The output will be `true` for `person1.equals(person2)` since they have the same `name` & `age`, & `false` for `person1.equals(person3)` since they have different `name` & `age`.

hashCode() method

The hashCode() method is another important method in Java that is used in conjunction with the equals() method. It returns an integer value that represents the hash code of an object. The hash code is used by hash-based data structures like HashMap, HashSet, & Hashtable to store & retrieve objects efficiently.

The hashCode() method is defined in the Object class, & its default implementation returns a unique integer value for each object based on its memory address. However, similar to the equals() method, the hashCode() method can be overridden in custom classes to provide a more meaningful hash code based on the objects' properties or attributes.

Syntax

The syntax for the hashCode() method is as follows:

public int hashCode() {
    // hash code generation logic here
}


To override the hashCode() method in your custom class, you need to follow these rules:

1. The method must be declared as public.
 

2. The method must not take any parameters.
 

3. The method must return an integer value.


Inside the method, you write the logic to generate a hash code based on the object's relevant properties or attributes. It is important to ensure that if two objects are considered equal according to the equals() method, they must have the same hash code.

The general contract of hashCode is:

1. Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
 

2. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

 

3. It is not required that if two objects are unequal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.


It is generally necessary to override the hashCode method whenever the equals method is overridden, to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

Frequently Asked Questions

What happens if I don't override the equals() method in my class?

If you don't override the equals() method, the default implementation from the Object class will be used, which compares the memory addresses of the objects rather than their content.

Can I override the equals() method without overriding the hashCode() method?

While it is possible to override equals() without overriding hashCode(), it is strongly recommended to override both methods together to maintain the general contract between equals() & hashCode().

What is the purpose of the hashCode() method?

The hashCode() method is used by hash-based data structures like HashMap, HashSet, & Hashtable to efficiently store & retrieve objects. It provides a way to generate a unique integer value for each object based on its properties or attributes.

Conclusion

In this article, we learned about the equals() & hashCode() methods in Java. We talked about their basics, syntax, and principles, with examples. The equals() method is used to compare two objects for equality based on their properties or attributes, while the hashCode() method generates a unique integer value for each object. Overriding these methods correctly is crucial for the proper functioning of hash-based data structures & maintaining the expected contract for object equality. 

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass