# Why is 31 taken in finding the hashCode of String?

Avinash Haridasu
Ranch Hand
Posts: 31
/**
* Returns a hash code for this string. The hash code for a
* <code>String</code> object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] // Line 1
* </pre></blockquote>
* using <code>int</code> arithmetic, where <code>s[i]</code> is the
* <i>i</i>th character of the string, <code>n</code> is the length of
* the string, and <code>^</code> indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/

public int hashCode() {
int h = hash;
if (h == 0 && count > 0) {
int off = offset;
char val[] = value;
int len = count;

for (int i = 0; i < len; i++) {
h = 31*h + val[off++]; // Line: 2
}
hash = h;
}
return h;
}

From Line 1 and Line 2 of the above we can find that 31 is used in finding the hashCode() of a string.

But why is it only 31 ???

Wouter Oet
Saloon Keeper
Posts: 2700
I'm not exactly sure why but I'm pretty sure it has got something to do with the fact that it is a prime number.

Jaikiran Pai
Marshal
Posts: 10447
227

Campbell Ritchie
Sheriff
Posts: 49367
62
It might be worth a look at the Joshua Bloch and Bruce Eckel links in this post.

Campbell Ritchie
Sheriff
Posts: 49367
62
That Wordpress article Jaikiran Pai quoted is better than my links.