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 thei
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?