Sobes.tech
Junior — Middle

Explain the differences between the equals() and hashCode() methods in Java and why they are needed together.

sobes.tech AI

Answer from AI

The equals() and hashCode() methods in Java are related to object comparison and their use in collections.

  • equals() determines whether two objects are equal in terms of content (logically). By default, in the Object class, it compares references (i.e., whether the objects are the same in memory), but it is usually overridden to compare the contents.

  • hashCode() returns an integer value — the hash code of the object. It is used, for example, in hash tables (HashMap, HashSet) for quick lookup.

It is important that if two objects are considered equal according to equals(), they must have the same hashCode(). This rule ensures the correct operation of hash-based collections.

Example:

class Person {
    String name;
    int age;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person)) return false;
        Person p = (Person) o;
        return age == p.age && name.equals(p.name);
    }

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

Here, equals() compares the fields, and hashCode() returns a hash based on the same fields, ensuring consistency.