Sobes.tech
Junior — Middle

Miks on soovitatav klassi määratlemisel ühiselt rakendada meetodid equals() ja hashCode()?

sobes.tech AI

Vastus AI-lt

The methods equals() and hashCode() are related and must be implemented together to ensure correct behavior of objects in collections such as HashMap, HashSet, and others based on hashing.

If two objects are considered equal by equals(), then their hashCode() must return the same value. Otherwise, collections may not work correctly: for example, an object may not be found in the hash table even if it exists.

Example:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    MyClass myClass = (MyClass) o;
    return id == myClass.id;
}

@Override
public int hashCode() {
    return Objects.hash(id);
}

This joint implementation guarantees consistency and correct operation of objects in collections.