Junior — Middle
Have you ever overridden the hashCode method in your code?
sobes.tech AI
Answer from AI
Yes, overriding the hashCode method in Java is a common practice, especially when overriding the equals method. It is necessary for the correct functioning of objects in hash-based collections such as HashMap or HashSet.
Rules for overriding hashCode:
- If two objects are equal according to
equals, then theirhashCodemust be the same. - A good implementation should distribute hashes evenly to reduce collisions.
Example of overriding hashCode and equals:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyClass myClass = (MyClass) o;
return Objects.equals(field1, myClass.field1) &&
Objects.equals(field2, myClass.field2);
}
@Override
public int hashCode() {
return Objects.hash(field1, field2);
}
Using Objects.hash simplifies creating a hash code based on the object's fields.