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

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

    Neil Coffey explains why 31 is used under Ironing out the bias.

    Basically using 31 gives you a more even set-bit probability distribution for the hash function.

提交回复
热议问题