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

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

    In latest version of JDK, 31 is still used. https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/String.html#hashCode()

    The purpose of hash string is

    • unique (Let see operator ^ in hashcode calculation document, it help unique)
    • cheap cost for calculating

    31 is max value can put in 8 bit (= 1 byte) register, is largest prime number can put in 1 byte register, is odd number.

    Multiply 31 is <<5 then subtract itself, therefore need cheap resources.

提交回复
热议问题