Middle
What are the rules for overriding hashCode and equals methods in Java?
sobes.tech AI
Answer from AI
For the correct operation of collections and other mechanisms based on object comparison (e.g., HashMap, HashSet), the following rules must be observed:
- Reflexivity (
equals): For any non-null referencex,x.equals(x)should returntrue. - Symmetry (
equals): For any non-null referencesxandy,x.equals(y)should returntrueonly ify.equals(x)returnstrue. - Transitivity (
equals): For any non-null referencesx,y, andz, ifx.equals(y)returnstrueandy.equals(z)returnstrue, thenx.equals(z)should returntrue. - Consistency (
equals): For any non-null referencesxandy, multiple calls tox.equals(y)should consistently returntrueorfalse, provided no information used in comparisons has been modified. equalsandnull: For any non-null referencex,x.equals(null)should returnfalse.- Consistency between
equalsandhashCode: Ifx.equals(y)returnstruefor any two non-null referencesxandy, thenx.hashCode()should return the same value asy.hashCode(). - Consistency of
hashCode: Multiple calls tohashCode()for the same object during the execution of an application should consistently return the same integer value, provided no information used inequalscomparisons on the object has been modified. (It is not required to return the same value across different runs of the application).
Here is an example implementation:
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public boolean equals(Object o) {
// Adhere to null and reflexivity rules
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
// Cast types
Person person = (Person) o;
// Compare significant fields
return age == person.age &&
Objects.equals(name, person.name); // Use Objects.equals for null-safe string comparison
}
@Override
public int hashCode() {
// Generate hash code based on significant fields
return Objects.hash(name, age); // Use Objects.hash for convenience and correctness
}
}