Sobes.tech
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:

  1. Check that the object is not null and belongs to the same class.
  2. Compare the significant fields that define object equality.
  3. 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.