Sobes.tech
Middle+

How do you determine which fields should be included in equals and hashCode?

sobes.tech AI

Answer from AI

When determining which fields to include in the equals and hashCode methods, it is important to consider which fields define the logical identity of the object. Usually, in equals and hashCode, include those fields that unambiguously identify the object from a business logic perspective.

For example:

  • If the object represents an entity with a unique identifier (e.g., ID), then it is sufficient to use only this ID.
  • If there is no unique ID, then include a set of fields that together unambiguously characterize the object.

It is important that the fields involved in equals are also involved in hashCode to maintain the contract between these methods.

Example:

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

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

Here, only the id field is used, as it uniquely identifies the Person object.