Sobes.tech
Junior — Middle

How is the equals method related to the hashCode method in the Java contract, and why is this important for the correct operation of collections?

sobes.tech AI

Answer from AI

In Java, there is an important contract between the equals and hashCode methods: if two objects are considered equal by the equals method, they must have the same hashCode. This rule is necessary for the correct functioning of hash-based collections such as HashMap, HashSet.

If this contract is violated, for example, if two equal objects have different hash codes, collections may behave incorrectly — an object might not be found in the hash table even if it exists there.

Example:

class Person {
    private String name;
    private int 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 == person.id && name.equals(person.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, id);
    }
}

Here, equals and hashCode are consistent: if two Person objects are equal, their hash codes will also match.