Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

In Java, the methods hashCode() and equals() are closely related and used for object comparison and working with collections like HashMap and HashSet.

  • The equals() method determines whether two objects are logically equal.
  • The hashCode() method returns an integer hash code, used for quick lookup in hash-based collections.

A key rule is that if two objects are considered equal by equals(), they must return the same hashCode(). Violating this rule can lead to incorrect behavior of hash-based collections.

Example:

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null || getClass() != obj.getClass()) return false;
    MyClass other = (MyClass) obj;
    return this.id == other.id;
}

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

Here, objects are considered equal if they have the same id field, and hashCode() is computed based on this field.

What is the relationship between the hashCode and… - sobes.tech