Sobes.tech
Junior — Middle

How are the equals and hashCode methods related in Java, and why is it important to implement them correctly together?

sobes.tech AI

Answer from AI

In Java, the equals and hashCode methods are closely related and should be implemented consistently so that objects work correctly in hash-based collections, such as HashMap or HashSet.

Rules:

  • If two objects are equal according to equals(), they must have the same hashCode().
  • If hashCode() of objects is different, they are definitely not equal.

Incorrect implementation can lead to objects that are considered equal being stored in different hash buckets, which will break search and delete logic.

Example of correct implementation:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    MyClass myClass = (MyClass) o;
    return field1.equals(myClass.field1) && field2 == myClass.field2;
}

@Override
public int hashCode() {
    return Objects.hash(field1, field2);
}