Junior — Middle
How is the hash value for an object calculated?
sobes.tech AI
Answer from AI
In Java, the hashCode() method computes the hash value of an object, which is typically used for quick lookup in collections such as HashMap or HashSet. By default, the method returns an integer value based on the internal state of the object.
For correct operation, it is important to override hashCode() together with equals(), so that objects considered equal have the same hash.
Example of overriding for a class with two fields:
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (field1 != null ? field1.hashCode() : 0);
result = 31 * result + (field2 != null ? field2.hashCode() : 0);
return result;
}