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

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

    I'm not sure, but I would guess they tested some sample of prime numbers and found that 31 gave the best distribution over some sample of possible Strings.

提交回复
热议问题