Junior — Middle
Why is it important to override the hashCode method in your classes?
sobes.tech AI
Answer from AI
Overriding the hashCode method is important when you create your own classes, especially if you also override the equals method. In Java, the contract between these methods states: if two objects are equal according to equals, then their hashCode must be the same. This is critical for the correct functioning of hash-based collections such as HashMap, HashSet.
If you do not override hashCode, objects that are considered equal may have different hash codes, which can lead to errors when searching, deleting, or adding to collections.
Example of overriding:
@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();
}
Here, field is a key field that determines object equality.