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
- Reflexivity: The
equals()method should be reflexive, which means thatx.equals(x)should returntrue. - Symmetry: The
equals()method should be symmetric, which means thatx.equals(y)should return the same result asy.equals(x). - Transitivity: If
x.equals(y)andy.equals(z)aretrue, thenx.equals(z)should also betrue. - Consistency: The
equals()method should be consistent, which means that multiple invocations ofx.equals(y)should return the same result as long as the objects being compared are not modified. - Null comparison: The
equals()method should returnfalsewhen the argument isnull. (Note: invokingequals()on anullreference throwsNullPointerException.)
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);
}
}