Sobes.tech
Junior — Middle

In which cases is it necessary to override the hashCode() method in Java to ensure correct operation with collections?

sobes.tech AI

Answer from AI

The hashCode() method in Java should be overridden when you override the equals() method. This is important for the correct functioning of objects in collections that use hashing, such as HashMap, HashSet, and Hashtable.

If equals() indicates that two objects are equal, their hashCode() must also return the same value. Otherwise, hash-based collections may work incorrectly: for example, they may not find an object or may store duplicates.

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);
}

Here, id is a field that determines object equality. Without overriding hashCode(), objects with the same id might have different hashes, which would break collection behavior.