String's hash code is computed as:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
using int
arithmetic, where s[i]
is the i
-th character of the string, n
is the length of the string, and ^
indicates exponentiation. (The hash value of the empty string is zero.)
Hence, the overflow of this integer computation can easily occur, resulting in negative according to Java Language specification-15.8.2:
If an integer addition overflows, then the result is the low-order
bits of the mathematical sum as represented in some sufficiently large
two's-complement format. If overflow occurs, then the sign of the
result is not the same as the sign of the mathematical sum of the two
operand values.