Junior — Middle
Kuidas rakendad objektide võrdlusvõrdlust meetodi equals abil?
sobes.tech AI
Vastus AI-lt
To correctly compare objects in Java using the equals method, you need to override this method in your class, considering all significant fields that determine object equality. General recommendations:
- Check that the object is not
null. - Check that the objects are of the same class.
- Compare all fields that influence equality.
Example implementation for the Person class:
@Override
public boolean equals(Object obj) {
if (this == obj) return true; // reference equality check
if (obj == null || getClass() != obj.getClass()) return false; // null and class check
Person other = (Person) obj;
return Objects.equals(name, other.name) && age == other.age;
}
It is also recommended to override hashCode when overriding equals for correct behavior in collections.