The JDK documentation for java.lang.String.hashCode()
famously says:
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, wheres[i]
is the *i
*th character of the string,n
is the length of the string, and^
indicates exponentiation.
The standard implementation of this expression is:
int hash = 0;
for (int i = 0; i < length; i++)
{
hash = 31*hash + value[i];
}
return hash;
Looking at this makes me feel like I was sleeping through my algorithms course. How does that mathematical expression translate into the code above?
unroll the loop. Then you get:
int hash = 0;
hash = 31*hash + value[0];
hash = 31*hash + value[1];
hash = 31*hash + value[2];
hash = 31*hash + value[3];
...
return hash;
Now you can do some mathematical manipulation, plug in 0 for the initial hash value:
hash = 31*(31*(31*(31*0 + value[0]) + value[1]) + value[2]) + value[3])...
Simplify it some more:
hash = 31^3*value[0] + 31^2*value[1] + 31^1*value[2] + 31^0*value[3]...
And that is essentially the original algorithm given.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With