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]using
intarithmetic, wheres[i]is the ith character of the string,nis 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?
According to Joshua Bloch’s Effective Java, Second Edition (a book that can’t be recommended enough, and which I bought thanks to continual mentions on Stack Overflow):
(from Chapter 3, Item 9: Always override
hashCodewhen you overrideequals, page 48)