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?
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With