Open In App

Importance of hashCode() Method in Java

Last Updated : 06 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the hashCode() method tells how objects are stored and compared when we work with collections like HashMap, HashSet, and HashTable. This method returns an integer value, which is known as a hash code, and with the help of this hash code, the program can easily access objects.

In this article, we are going to discuss the importance of hashCode() method in Java.

Prerequisite:

HashMap and HashSet use hashing to manipulate data. They use the hashCode() method to check hash values. The default implementation of hashCode() in the Object class returns distinct integers for different objects. Sometimes, we have to implement hashCode() method in our program.

Java Program to Demonstrates hashCode() and equals() Methods

Example:

Java
// Java program to illustrate use
// of hashcode() and equals() method
import java.util.*;

public class Name {
    private final String first, last;
    public Name(String first, String last)
    {
        this.first = first;
        this.last = last;
    }
    public boolean equals(Object o)
    {
        if (!(o instanceof Name))
            return false;
        Name n = (Name)o;
        return n.first.equals(first) && n.last.equals(last);
    }
    public static void main(String[] args)
    {
        Set<Name> s = new HashSet<Name>();
        s.add(new Name("Shubham", "Juneja"));
        System.out.println(
            s.contains(new Name("Shubham", "Juneja")));
    }
}

Output
false

Explanation: In the above example, a Name instance consists of a first name and a last name. Two Name instances are considered equal, as computed by the equals() method, if both their first name and last name are equal. The equals() method compared the first and the last name. Two strings are equal if they consist of the same characters in the same order. Therefore, two Name instances are equal if they represent the same name.

For example:

new Name("Shubham", "Juneja").equals(new Name("Shubham", "Juneja"))

The will return true, because the main method of the program creates two Name instances, both representing Shubham Juneja.

Now, the most important question arises

Why Does the Program Print false?

The program should print true because the two instances represent the same name, but it prints false because the Name instance does not override the hashcode() method. The Name class uses the default hashCode() method two Name instances that are equal by equals() may have different hash codes and this causes the HashSet to not find the second instance, even though they are logically the same. In hash-based collections, the hash code decides which basket an object belongs to. If the hash codes are different, the objects are placed in different basket and not compared for equality and this leads to incorrect result

To fix this, we need to override the hashCode() method so equal objects have the same hash code.

Solution: Override hashCode() Method

To fix the issue, we need to override the hashCode() method to make sure that equal objects produce the same hash value. We can simply do this:

@Override

public int hashCode() {

return 63 * first.hashCode() + last.hashCode();

}

Now, when we run the program, the HashSet correctly identify the two Name instances are equal and then it will print true.

Correct Code:

Java
import java.util.*;

public class Name {
    private final String first, last;

    // Constructor to initialize first and last names
    public Name(String first, String last) {
        this.first = first;
        this.last = last;
    }

    // Overriding equals method to compare Name objects
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Name))
            return false;
        Name n = (Name) o;
        return n.first.equals(first) && n.last.equals(last);
    }

    // Overriding hashCode method to ensure equal objects have the same hash code
    @Override
    public int hashCode() {
        return 63 * first.hashCode() + last.hashCode();
    }

    public static void main(String[] args) {
        Set<Name> s = new HashSet<Name>();
        s.add(new Name("Shubham", "Juneja"));
        // Output will now be true
        System.out.println(s.contains(new Name("Shubham", "Juneja")));  
    }
}

Output
true

Practice Tags :

Similar Reads