2013-03-18 147 views
0

哈希码值为什么相同?哈希码值相同

public static void main(String args[]) 
{ 
    String s1="abc"; 
    String s2=new String("abc"); 
    System.out.println("Hashcode s1-:"+ s1.hashCode()); 
    System.out.println("Hashcode s2-:"+ s2.hashCode()); 
    if(s1==s2){ 
     System.out.println("==true:"); 
    } 
} 

输出

Hashcode s1-:96354 
Hashcode s2-:96354 
+1

因为字符串是相同的。 – 2013-03-18 09:27:51

+0

在这里看到更多的信息http://stackoverflow.com/questions/785091/consistency-of-hashcode-on-a-java-string – 2013-03-18 09:28:34

+0

@Sudhanshu他呼吁新的String,所以他们不是指同一个对象,因此,为什么==返回false。 – DaveJohnston 2013-03-18 09:29:37

回答

7

为两个相等的对象的哈希码应该相等。

在这种情况下,对象是字符串,它们被认为是相等的,因为它们保持相同的字符序列“abc”。

如果你想要一个基于对象身份而不是相等的哈希码,请使用System.identityHashCode()

+1

我认为他的困惑在于他对'=='的测试返回false。 – DaveJohnston 2013-03-18 09:31:39

+0

感谢您的宝贵答案 – 2013-03-18 09:36:05

+0

@DaveJohnston你是对的,请帮我 – 2013-03-18 09:40:29

3

为什么他们不一样? hashcode是根据字符串的内容计算的,因此它们对于两者都是相同的。

==比较对象引用,并且因为您使用new String而不是s2引用是不相同的。

您应该使用equals方法根据字符串的值测试字符串的相等性。

0

这是代码...因此结果是两个相同的等于对象:

public int hashCode() { 
int h = hash; 
    int len = count; 
if (h == 0 && len > 0) { 
    int off = offset; 
    char val[] = value; 

     for (int i = 0; i < len; i++) { 
      h = 31*h + val[off++]; 
     } 
     hash = h; 
    } 
    return h; 
} 
2

由于哈希码使用这需要在只存在于字符串中的字符的公式计算。 String中的相同字符将产生相同的哈希码

Javadoc为计算公式。

0

根据规则,这些equals方法的对象返回true,应该具有相同的哈希码。

的字符串
0

Hashcode方法是基于它的字符来计算,所以是equals()

它被计算为

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 

其中s [i]是每个字符为0<=i<n和n是其长度。

你的字符串都有相同的内容,因此哈希码是相同的。

0

String class拥有自己的hashcode方法在里面实现。其方法将计算哈希码为:s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

因此对于相同的字符序列哈希码将是相同的。

0

的JVM不创建一个新的字符串,如果这个已经存在,它只是返回的参考。当您尝试更改其中一个变量中的实际字符串时,将会创建一个新字符串。 你可以检查它调试应用程序,String对象将有不同的内存地址,但里面的值将具有完全相同的内存地址。