Sobes.tech
Junior — Middle

When and why should the hashCode method be overridden in a class?

sobes.tech AI

Answer from AI

The hashCode method should be overridden in a class if you override the equals method. This is necessary to maintain the contract between these methods: if two objects are equal according to equals, then their hash codes must be the same. Otherwise, objects may behave incorrectly in hash-based collections, such as HashMap or HashSet.

Example:

@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) && field2 == other.field2;
}

@Override
public int hashCode() {
    return Objects.hash(field1, field2);
}

Without overriding hashCode, objects that are equal according to equals may have different hash codes, which can lead to errors when used in hash data structures.

When and why should the hashCode method be overridden… - sobes.tech