• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why is 31 taken in finding the hashCode of String?

 
Avinash Haridasu
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
/**
* 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
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50171
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It might be worth a look at the Joshua Bloch and Bruce Eckel links in this post.
 
Campbell Ritchie
Sheriff
Pie
Posts: 50171
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That Wordpress article Jaikiran Pai quoted is better than my links.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic