Monday, September 7, 2026

Understanding hashCode() in Java


Understanding hashCode() in Java

The hashCode() method is defined in the Object class and is used to return a hash code value for an object.

It is especially important when working with hash-based collections such as HashMap, HashSet, and Hashtable.

public int hashCode()


General contract of hashCode()

There are a few important rules that should be followed:

If hashCode() is called multiple times on the same object during a Java application execution, it should return the same integer value as long as the information used by equals() has not changed.

If two objects are considered equal according to the equals() method, they must return the same hash code. Two objects that are not equal do not have to return different hash codes. Different objects can have the same hash code. This is called a hash collision.

Having fewer collisions can improve the performance of hash-based collections.

Example

Consider the following class:

public class Employee {

    private int id;
    private String name;

    public Employee(int id, String name) {
        this.id = id;
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof Employee)) {
            return false;
        }

        Employee employee = (Employee) obj;

        return id == employee.id;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(id);
    }
}

Here, id is used to determine whether two Employee objects are equal. Therefore, the same id is also used to calculate the hash code.

This is important because:

Employee e1 = new Employee(101, "John");
Employee e2 = new Employee(101, "David");
System.out.println(e1.equals(e2)); // true 
System.out.println(e1.hashCode());
System.out.println(e2.hashCode());



Since both objects have the same id, they are considered equal and must have the same hash code.


Why is hashCode() important?

Hash-based collections use the hash code to efficiently locate objects.


For example:

HashSet<Employee> employees = new HashSet<>(); 

employees.add(new Employee(101, "John"));

employees.add(new Employee(101, "David"));

System.out.println(employees.size());


Because the two objects are considered equal based on id, the HashSet treats them as the same element.


Important point

  1. If you override equals(), you should also override hashCode().
  2. The basic rule to remember is:
  3. If a.equals(b) is true, then a.hashCode() must equal b.hashCode().
  4. However, the reverse is not required:
  5. Same hash code does not mean that two objects are equal.

No comments:

Post a Comment