Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

In Java, the equals and hashCode methods are linked by a contract that guarantees the correct functioning of objects in hash-based collections (such as HashMap, HashSet).

Main rules:

  • If two objects are equal according to the equals method (i.e., a.equals(b) returns true), then they must have the same hashCode.
  • If the hashCode of two objects is different, then they are definitely not equal.

This is necessary so that when searching for an object in a hash structure, the correct bucket is first located by hashCode, and then objects are compared using equals.

Example:

class Person {
    private String id;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return id.equals(person.id);
    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }
}
What is the relationship between hashCode and equals… - sobes.tech