Junior — Middle
How can the main version of the hashCode method be implemented in a class?
sobes.tech AI
Answer from AI
The main version of the hashCode method in Java should provide a uniform distribution of hashes and consider all significant fields of the object that participate in comparison via equals. It is usually implemented as follows:
- Use a non-zero initial number, such as 17 or 31.
- For each significant field, compute its hash (directly for primitives, by calling
hashCode()for objects, considering null). - Iteratively combine the hashes of the fields by multiplying by a prime number (often 31) and adding.
Example implementation:
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (field1 != null ? field1.hashCode() : 0);
result = 31 * result + field2;
result = 31 * result + (int) (field3 ^ (field3 >>> 32)); // for long
return result;
}
This approach minimizes collisions and complies with the hashCode contract in Java.