更新时间:2023-11-26 21:35:10
String的 哈希码 计算如下:
String's hash code is computed as:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
使用 int
算术,其中 s [i]
是字符串的 i
-th字符, n
是字符串的长度, ^
表示 exponentiation 。 (空字符串的哈希值为零。)
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.)
因此,这个整数计算的溢出很容易发生,根据 Java语言规范-15.8.2 :
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.