Junior — Middle
Can you explain what the hashCode method in the Java contract is and how it is used?
sobes.tech AI
Answer from AI
In Java, the hashCode() method returns an integer value (hash code) of an object, which is used for quick search and comparison of objects in collections such as HashMap, HashSet, and others.
The contract of the hashCode() method includes the following rules:
- If two objects are equal according to the
equals()method, they must have the same hash code. - If objects are not equal, their hash codes can be the same, but it is desirable for them to be different to reduce collisions.
- The hash code of an object should remain unchanged unless the object is modified in a way that affects equality comparison via
equals().
Example of overriding hashCode() and equals():
@Override
public int hashCode() {
return Objects.hash(field1, field2);
}
@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) && Objects.equals(field2, other.field2);
}
Thus, hashCode() helps efficiently store and search objects in hash data structures.