Sobes.tech
Junior — Middle

What are the main principles of the relationship between the equals and hashCode methods in Java?

sobes.tech AI

Answer from AI

Main principles of the relationship between equals and hashCode in Java:

  • If two objects are equal according to equals, their hashCode must be the same.
  • If the hashCode of two objects is different, equals must return false.
  • If equals returns false, hashCode can be the same, but this is undesirable as it degrades the performance of hash-based structures.

This ensures the correct operation of collections that use hashing (HashMap, HashSet), where hashCode determines the bucket, and equals provides the exact comparison of objects.

Example:

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

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

Here, equals and hashCode are based on the same field id, which ensures their consistency.