Junior — Middle
What aspects should be considered when overriding the equals method in Java?
sobes.tech AI
Answer from AI
When overriding the equals method in Java, it is important to adhere to the following aspects:
- Reflexivity: An object must be equal to itself (
x.equals(x)should returntrue). - Symmetry: If
x.equals(y)returnstrue, theny.equals(x)should also returntrue. - Transitivity: If
x.equals(y)andy.equals(z)returntrue, thenx.equals(z)should also returntrue. - Consistency: Multiple calls to
equalsshould return the same result if the objects have not changed. - Null check:
x.equals(null)should returnfalse.
Additionally, when overriding equals, it is necessary to also override hashCode so that objects considered equal by equals have the same hash code.
Example of a correct override:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyClass myClass = (MyClass) o;
return Objects.equals(field1, myClass.field1) &&
Objects.equals(field2, myClass.field2);
}
@Override
public int hashCode() {
return Objects.hash(field1, field2);
}