Why does Java's hashCode() in String use 31 as a multiplier?

前端 未结 13 2254
星月不相逢
星月不相逢 2020-11-22 01:34

Per the Java documentation, the hash code for a String object is computed as:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
<         


        
13条回答
  •  名媛妹妹
    2020-11-22 02:08

    Bloch doesn't quite go into this, but the rationale I've always heard/believed is that this is basic algebra. Hashes boil down to multiplication and modulus operations, which means that you never want to use numbers with common factors if you can help it. In other words, relatively prime numbers provide an even distribution of answers.

    The numbers that make up using a hash are typically:

    • modulus of the data type you put it into (2^32 or 2^64)
    • modulus of the bucket count in your hashtable (varies. In java used to be prime, now 2^n)
    • multiply or shift by a magic number in your mixing function
    • The input value

    You really only get to control a couple of these values, so a little extra care is due.

提交回复
热议问题