Why did you choose 31 for multiplication in the hashcode () implementation?

Possible duplicate:
Why does hashCode () in String use 31 as a multiplier?
Why use a prime in hashCode?

From Effective Java Point 9: Always redefine hashCode when you redefine equals , consider the following appropriate code snippet that redefines hashcode () defined in the Object class.

public final class PhoneNumber {
  private final short areaCode;
  private final short prefix;
  private final short lineNumber;
  ......//Rest ignored on purpose
  .....

private volatile int hashCode; // (See Item 71)
@Override public int hashCode() {
   int result = hashCode;
   if (result == 0) {
    result = 17;
    result = 31 * result + areaCode;
    result = 31 * result + prefix;
    result = 31 * result + lineNumber;
    hashCode = result;
   }
 return result;
 }
}

, "17". , , hashcode(). 31 . - , ? , 31, . , .

31 , . , , 2 . , .

+5
3

, . , . , -, .

+10

, . 9, , 3.

AFAIK 31 , 31 , , 6 -. , 61 (, 64), 5 , 13 ( 16), .

+3

, , . - X X * B ^ k, B 31, k X . . , B ^ k k.

, " " Gonnet Baeza-Yates, 3.3.1 "Pratical hashing functions", : " B = 131, B ^ mod 2 ^ k 8 <= k <= 64." , 31 mod 2 ^ 32? , 31 Sparc, 131 .

+1

All Articles