Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating hashCode from multiple fields? [duplicate]

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?

like image 592
Duncan Avatar asked May 29 '13 22:05

Duncan


1 Answers

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();
}
like image 106
Sergey Kalinichenko Avatar answered Sep 30 '22 02:09

Sergey Kalinichenko