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

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

    This is because 31 has a nice property – it's multiplication can be replaced by a bitwise shift which is faster than the standard multiplication:

    31 * i == (i << 5) - i
    

提交回复
热议问题