Sobes.tech
Junior — Middle

Why is it necessary to override the hashCode() method in Java when using objects in hash tables?

sobes.tech AI

Answer from AI

In Java, the hashCode() method is used to compute the hash code of an object, which determines the bucket in the hash table where the object will be placed. If you override the equals() method, you must also override hashCode() to ensure consistency:

  • If two objects are equal according to equals(), their hashCode() must be the same.
  • If hashCode() is not overridden, objects that are equal according to equals() may have different hash codes, leading to incorrect behavior of hash tables (e.g., HashMap, HashSet).

Without proper overriding of hashCode(), objects may not be found in collections even if they are logically equal, violating the collection contract and causing errors.

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 field.equals(myClass.field);
}

@Override
public int hashCode() {
    return field.hashCode();
}