使用String hashCode()方法? [英] Use String hashCode() Method?
问题描述
来自链接:
http ://www.tutorialspoint.com/java/java_string_hashcode.htm
但是我无法理解哈希码。
But i cant understand about the hashcode .
以下是一个例子:
public class StringDemo {
public static void main(String args[]){
String strob1="first string";
System.out.println(strob1.hashCode());
}
}
这个简单的程序给我输出: -5468287
This simple program give me output:-5468287
任何人都可以告诉我:
它如何给我输出: -5468287
?
Can anyone tell me :
How it give me output:-5468287
?
推荐答案
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.
这篇关于使用String hashCode()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!