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

前端 未结 13 2268
星月不相逢
星月不相逢 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:26

    By multiplying, bits are shifted to the left. This uses more of the available space of hash codes, reducing collisions.

    By not using a power of two, the lower-order, rightmost bits are populated as well, to be mixed with the next piece of data going into the hash.

    The expression n * 31 is equivalent to (n << 5) - n.

提交回复
热议问题