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

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

    Goodrich and Tamassia computed from over 50,000 English words (formed as the union of the word lists provided in two variants of Unix) that using the constants 31, 33, 37, 39, and 41 will produce fewer than 7 collisions in each case. This may be the reason that so many Java implementations choose such constants.

    See section 9.2 Hash Tables (page 522) of Data Structures and Algorithms in Java.

提交回复
热议问题