【发布时间】:2015-12-02 01:45:18
【问题描述】:
请按照以下代码,
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 具有相同的 hashcode 并通过 equals 限定,但通过 == 不相等,为什么?
是不是因为 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
}
}
在上面的示例中,两个员工对象也具有相同的哈希码并通过 .equals 方法限定相等性,但它们在 == 中的相等性仍然失败。
在上述两种情况下,为什么它们是两个不同的对象?请解释
【问题讨论】:
-
因为 '==' 检查它们在内存中的位置是否相等。它们在内存方面是不同的,但是通过实现 hashcode 和 equals 你说你希望它们在语义上是相等的。
标签: java