algorithm - Proof: why does java.lang.String.hashCode()'s implementation match its documentation? -
The JDK documentation for
says:
The calculation of the hash code for a string object
s [0] * 31 ^ (n-1) + s [1] * 31 ^ (n -2) + ... + s [n-1] < Using the / code>
intarithmetic, wheres [i]is the string of *i* of the string ,Nis the length of the string, and^indicates exponentiation.
The standard implementation of this expression is:
int hash = 0; For (int i = 0; i & lt; length; i ++) {hash = 31 * hash + value [i]; } Return hashes; I feel like I was sleeping through my algorithm course. How does mathematical expression translate into the above code?
I'm not sure if you remember it, "^ ^ Exponentation indicates" But not xor).
Each time the loop is added, the previous value of the hash is added in 31 again before moving forward element of value .
One can prove that these things are equal to induction, but I think an example can be more obvious:
We are saying a 4-four string Let's unlock the loop with:
hash = 0; Hash = 31 * hash + value [0]; Hash = 31 * hash + value [1]; Hash = 31 * hash + value [2]; Hash = 31 * hash + value [3]; Now in each statement, by substituting each value of this hash into the following statement:
hash = 31 * (31 * (31 * (31 * 0 + value [0]) + value [1]) + value [2]) + value [3]; 31 * 0 is very simple: hash = 31 * (31 * ([31] value [0] + value [1]) + value [2]) + value [3 ];
Now multiply two internal words by the second 31:
Now multiply these three words:
hash = 31 * 31 * 31 * value [0] + 31 * 31 * value [1] ] + 31 * value [2] + value [3];
and convert to exponents (not actually Java):
hash = 31 ^ 3 * value [0] + 31 ^ 2 * value [1] + 31 ^ 1 * value [2] + value [3];
Comments
Post a Comment