7

How do I generate a hashCode from two fields in my class?

For example, I want Pair classes with the same objects V to have the same hashCode:

public class Pair<V> {
    V from, to;
}

Should I multiply their hashCodes together? Add them? Multiply them with a prime?

Duncan
  • 984
  • 10
  • 20

1 Answers1

13

One way to do it is adding the hash code of the first field to hash code of the second field, multiplied by a small prime number, like this:

public int hashCode() {
    return 31 * from.hashCode() + to.hashCode();
}
Dan Grahn
  • 9,044
  • 4
  • 37
  • 74
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 5
    Should there be parentheses here? Seems the explanation does not match the code. – meijuh Jul 16 '14 at 15:38
  • No there is no parentheses – OrlandoL Aug 13 '19 at 19:59
  • Why 31 and not an even smaller prime, such as 2? – Trang Oul Feb 21 '22 at 12:08
  • @TrangOul There is no particular reason to use any specific prime. I would not pick 2, though, because it's the only even prime, so multiplying by it in the binary representation would amount to a simple shift. In other words, the result would be equivalent to `(from.hashCode() << 1) + to.hashCode()`. Although there is nothing particularly wrong with this approach, generally one would prefer more "mixing up" among the bits of the individual hash codes. – Sergey Kalinichenko Feb 21 '22 at 16:01