Advertisement
Beginner Java, equals(), hashCode() & toString() Contracts

What is the recommended way to combine multiple field values into a single hashCode() implementation, following the common formula used by IDE-generated code?

Short answer

A widely-used, well-distributed hashCode() combining formula starts with a nonzero seed (traditionally 17), then for each significant field repeatedly applies result = 31 * result + fieldHashCode -- this specific approach (using a prime multiplier like 31, chosen partly because…

Save Java mock interview
Advertisement
AModel answer
A widely-used, well-distributed hashCode() combining formula starts with a nonzero seed (traditionally 17), then for each significant field repeatedly applies result = 31 * result + fieldHashCode -- this specific approach (using a prime multiplier like 31, chosen partly because it can be efficiently computed via a bit-shift-and-subtract on older JVMs) helps spread hash values well across the available bucket range, minimizing collisions; Objects.hash() implements essentially this same formula internally, making it the simpler, preferred choice for most code rather than hand-rolling this pattern manually.
public class Point {
    private final int x, y;

    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + x;
        result = 31 * result + y;
        return result;
    }
    // Equivalent to: return Objects.hash(x, y);
}
Real-world example
An IDE's auto-generated hashCode() method for a multi-field class uses exactly this 31-multiplier accumulation pattern, matching the same well-established, well-distributed formula that Objects.hash() implements internally, chosen specifically for its good collision-avoidance properties across a wide range of typical field value distributions.
Likely follow-ups
  • Why is 31 specifically chosen as the multiplier rather than some other prime number?
  • How does this formula's collision-avoidance quality compare to simply XORing all the field hash codes together?
Related topics