Java 如果两个对象具有相同的hashCode,并且通过等于来限定相等,那么为什么它们会失败呢==

Java 如果两个对象具有相同的hashCode,并且通过等于来限定相等,那么为什么它们会失败呢==,java,Java,请按照下面的代码 String s1 = "ABC"; String s2 = new String("ABC"); String s3 = "ABC"; System.out.println(s1.hashCode()); // 64578 System.out.println(s2.hashCode()); // 64578 System.out.println(" s1 == s2 "+(s1 == s2)); // s1 =

请按照下面的代码

    String s1 = "ABC";
    String s2 = new String("ABC");
    String s3 = "ABC";

    System.out.println(s1.hashCode()); // 64578
    System.out.println(s2.hashCode()); // 64578     

    System.out.println(" s1 == s2 "+(s1 == s2)); //  s1 == s2 false
    System.out.println(" s1 == s3 "+(s1 == s3)); // s1 == s3 true
这里,字符串s1和s2都有相同的哈希代码,并通过等于进行限定,但通过==使相等失败,为什么

是不是因为s1和s2是不同的对象,尽管它们都有相同的哈希代码和eqauls的qalify,如果是的话,请解释一下为什么

另外,请看下面的例子

class Employee{
private Integer employeeCode;

Employee(Integer empCode){
    this.employeeCode = empCode;    
}

@Override
public int hashCode(){
    return this.employeeCode * 21;
}

public boolean equals(Object o){
    Employee emp = (Employee) o;

    return this.employeeCode.equals(emp.employeeCode);
}
} 

public class HashCodePractise01{


public static void main(String [] args){
    Employee e1 = new Employee(1);
    Employee e2 = new Employee(1);

    System.out.println(e1.hashCode()); // 21
    System.out.println(e2.hashCode()); // 21
    System.out.println("e1.equals(e2) "+(e1.equals(e2))); // e1.equals(e2) true 
    System.out.println("e1 == e2 "+(e1 == e2)); // e1 == e2 false
}
}
在上面的示例中,两个employee对象都有相同的hashcode,并通过.equals方法限定相等,但它们在==中仍然失败


在上述两种情况下,为什么它们是两个不同的对象?请解释

如果Java中的两个对象共享相同的内存位置,即如果它们实际上是同一个对象,那么它们的计算结果将仅为==


在您的第一个示例中,S1和S3是相等的,因为字符串是不可变的,因此,java可以在编译时将这些文本巧妙地转换为单个缓存字符串。我认为这是在编译时发生的,可能是在运行时。我对java细节有点模糊,如果有人知道的话,可以随意提供编辑。

要比较两个字符串,必须使用.equals和not==因为.equals比较字符串的值,而==比较两个对象,这两个对象无论如何都不是真的。

因为“==”检查它们在内存中的位置是否相等。它们在内存方面是不同的,但是通过实现hashcode和equals,您说您希望它们在语义上是相等的。