Junior — Middle
Can you explain the main rules for overriding the equals method in Java?
sobes.tech AI
Answer from AI
Main rules for overriding the equals method in Java:
- Reflexivity: an object must be equal to itself (x.equals(x) == true).
- Symmetry: if x.equals(y) == true, then y.equals(x) should also be true.
- Transitivity: if x.equals(y) == true and y.equals(z) == true, then x.equals(z) == true.
- Consistency: multiple calls to equals with the same objects should return the same result.
- Comparison with null: x.equals(null) should return false.
When overriding equals, it is also common to override hashCode so that objects equal according to equals have the same hashCode.
Example:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
MyClass other = (MyClass) obj;
return Objects.equals(field1, other.field1) && field2 == other.field2;
}