Why does Java's hashCode() in String use 31 as a multiplier?
Posted
by jacobko
on Stack Overflow
See other posts from Stack Overflow
or by jacobko
Published on 2008-11-18T16:39:43Z
Indexed on
2010/06/18
1:13 UTC
Read the original article
Hit count: 275
In Java, the hash code for a String
object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int
arithmetic, where s[i]
is the i
th character of the string, n
is the length of the string, and ^
indicates exponentiation.
Why is 31 used as a multiplier?
I understand that the multiplier should be a relatively large prime number. So why not 29, or 37, or even 97?
© Stack Overflow or respective owner