Junior — Middle
Can you explain the purpose of the hashCode method in the Object class in Java and how it is used?
sobes.tech AI
Answer from AI
The hashCode() method in the Object class in Java returns an integer value (hash code) of the object, which is used, for example, in hash tables (HashMap, HashSet) for quick lookup.
According to the contract, if two objects are equal according to the equals() method, then their hashCode() must return the same value. This is important for the correct functioning of hash-based collections.
By default, hashCode() returns a value related to the memory address of the object, but this method is often overridden to consider the content of the object.
Example of overriding:
@Override
public int hashCode() {
return Objects.hash(field1, field2);
}
Thus, hashCode() helps efficiently index objects in collections.