Sobes.tech
Junior — Middle

Why is it necessary to override the hashCode and equals methods when adding identical objects to a HashSet?

sobes.tech AI

Answer from AI

HashSet in Java uses a hash table to store elements. To correctly determine whether two objects are the same and avoid adding duplicates, HashSet relies on the hashCode() and equals() methods.

  • The hashCode() method computes the hash code of the object, which determines in which "bucket" of the hash table it will be placed.
  • The equals() method compares two objects for equality.

If you do not override these methods in your class, the default implementation from the Object class will be used, which compares objects by reference (i.e., two different objects with the same data will be considered different).

Therefore, to ensure HashSet correctly recognizes identical objects and prevents duplicates, you need to override hashCode() and equals() so that they consider the significant fields of the object.

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 field1.equals(myClass.field1) && field2.equals(myClass.field2);
}

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

Without this, HashSet can store multiple objects with the same data, which violates the set logic.