Sobes.tech
Middle

What is the relationship between the equals() and hashCode() methods in Java?

sobes.tech AI

Answer from AI

The contract is as follows:

  1. If two objects are equal according to the equals() method, then their hash codes returned by the hashCode() method must be equal.
  2. If two objects have the same hash code, it does NOT mean they are equal according to equals(). Hash collisions are possible.

This is critical for the correct functioning of hash-based collections (e.g., HashMap, HashSet). When searching or inserting an element, the hash code is used first to determine the potential "bucket," and then equals() is used to compare objects within that bucket. Violating the contract leads to incorrect behavior of such collections (elements may not be found or duplicated).

It is recommended to override both methods together, or neither, if the default behavior from Object is sufficient.

An example of correct overriding:

// Example class with overridden equals and hashCode
class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getters (not shown for brevity)

    @Override
    public boolean equals(Object o) {
        // Self-comparison check
        if (this == o) return true;
        // Null check and class comparison
        if (o == null || getClass() != o.getClass()) return false;
        
        Person person = (Person) o;

        // Comparison by significant fields
        if (age != person.age) return false;
        return name != null ? name.equals(person.name) : person.name == null;
    }

    @Override
    public int hashCode() {
        int result = name != null ? name.hashCode() : 0;
        result = 31 * result + age; // 31 is a prime number, suitable for hashing
        return result;
    }
}