Generating hashCode from multiple fields?

How to create a hash code from two fields in my class?

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

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

Should I multiply my hash codes together? Add them? Multiply them by simple?

+4
source share
1 answer

One way to do this is to add the hash code of the first field to the hash code of the second field, multiplied by a small prime number, for example:

 public int hashCode() { return 31 * from.hashCode() + to.hashCode(); } 
+7
source

Source: https://habr.com/ru/post/1483468/


All Articles