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?

2
  • a look at how lombok implements it might help Commented May 29, 2013 at 22:11
  • There are a ton of questions already on SO related to this. Was there something that wasn't clear? Commented May 29, 2013 at 22:11

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

Should there be parentheses here? Seems the explanation does not match the code.
No there is no parentheses
Why 31 and not an even smaller prime, such as 2?
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.