Junior — Middle
How should the equals() method be overridden in a class?
sobes.tech AI
Answer from AI
When overriding the equals() method in Java, it is important to follow several rules:
- Check that the object is not
nulland belongs to the same class. - Compare the significant fields that define object equality.
- Ensure symmetry, reflexivity, and transitivity.
Example of overriding:
@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) &&
Objects.equals(field2, other.field2);
}
It is also recommended to override hashCode() along with equals() to ensure correct behavior in collections.