Hashcode值相同

Mah*_*nde 0 java

为什么hashcode值相同?

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:");
    } 
}
Run Code Online (Sandbox Code Playgroud)

产量

Hashcode s1-:96354
Hashcode s2-:96354
Run Code Online (Sandbox Code Playgroud)

Jon*_*oni 7

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

在这种情况下,对象是字符串,它们被认为是相等的,因为它们具有相同的字符序列"abc".

如果您想要一个基于对象标识而不是使用相等的哈希码System.identityHashCode().