The multiplication in step 2.b makes the result depend on the order of the fields, yielding a much better hash function if the class has multiple similar fields. For example, if the multiplication were omitted from a
String hash function, all anagrams would have identical hash codes. The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance:
31 * i == (i << 5) - i. Mode...
Why using prime numbers. Besides that the other meaningful reason to choice a prime number is that has only one multiplier, while non-prime has at least two. That creates an extra combination for multiplication operator to result the same hash, and increases the chance of a collision.
Share this highlighthttp://www.safaribooksonline.com/a/effective-java-2nd/7667083/