W3docs

What issues should be considered when overriding equals and hashCode in Java?

When overriding the equals() and hashCode() methods in Java, you should consider the following issues:

When overriding the equals() and hashCode() methods in Java, you should consider the following issues:

equals() Contract

  1. Reflexivity: The equals() method should be reflexive, which means that x.equals(x) should return true.
  2. Symmetry: The equals() method should be symmetric, which means that x.equals(y) should return the same result as y.equals(x).
  3. Transitivity: If x.equals(y) and y.equals(z) are true, then x.equals(z) should also be true.
  4. Consistency: The equals() method should be consistent, which means that multiple invocations of x.equals(y) should return the same result as long as the objects being compared are not modified.
  5. Null comparison: The equals() method should return false when the argument is null. (Note: invoking equals() on a null reference throws NullPointerException.)

hashCode() Contract 6. Hash code stability: The hashCode() method should return the same value for an object as long as the object is not modified. 7. Hash code consistency with equals: If x.equals(y) is true, then x.hashCode() should be equal to y.hashCode().

Implementation Best Practices 8. Override together: It is also important to override the equals() and hashCode() methods together, as the hashCode() method is used in hash-based collections such as HashMap and HashSet. 9. Hash code uniqueness: It is not required, but it is recommended that different objects have different hash codes.

Example Implementation

import java.util.Objects;

public class Person {
    private final String name;
    private final int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

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

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