Implementing hashCode: Combining Field Hash Codes
What You'll Learn
You'll learn the standard formula using prime numbers to combine multiple fields' hash codes into a single, well-distributed hash code value.
Why Combine Field Hash Codes?
When implementing hashCode(), you need to include all fields used in your equals() method. But how do you merge multiple field hash codes into one integer? Simply adding them would be problematic—objects with the same field values in different orders would produce identical hash codes (like Point(3, 5) and Point(5, 3) both giving 8).
The Standard Formula
The widely-accepted approach uses a prime number multiplier (typically 31) with this pattern:
@Override
public int hashCode() {
int result = 17; // Starting prime
result = 31 * result + field1.hashCode();
result = 31 * result + field2.hashCode();
result = 31 * result + field3.hashCode();
return result;
}
For primitive fields, use their wrapper classes' hashCode() methods:
Integer.hashCode(intField)Boolean.hashCode(booleanField)- etc.
Why 31?
The number 31 is chosen because:
- It's prime (reduces hash collisions)
- It's odd (even numbers lose information when multiplied)
- The JVM can optimize
31 * ias(i << 5) - i(bit shift is faster than multiplication) - It's large enough to spread values but small enough to avoid overflow issues
Example with Multiple Fields
public class Person {
private String name;
private int age;
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
result = 31 * result + Integer.hashCode(age);
return result;
}
}
Key Takeaway: Combine field hash codes using the formula result = 31 * result + field.hashCode(), repeating for each field used in equals(), to create a well-distributed hash code that respects field order.