繁体   English   中英

Java中的对象身份与平等

[英]Object Identity and Equality in Java

请看下面的两个例子:

String a = new String("hello");
String b = new String("hello");
System.out.println("a.hashCode() - " + a.hashCode());
System.out.println("b.hashCode() - " + b.hashCode());
System.out.println("a == b - " + (a == b));
System.out.println("a.equals(b) - " + (a.equals(b)));

结果:

a.hashCode() - 99162322
b.hashCode() - 99162322
a == b - false
a.equals(b) - true

如果我理解正确,我有2个不同的对象,因为单词new创建了对象。 但是我们看到hashCode是相同的,这意味着我错了。 如果hashCode是相同的,我理解为什么a.equals(b)True

但是这段代码的输出:

int [] a = {1, 2, 3};
int [] b = {1, 2, 3};
System.out.println("a.hashCode() - " + a.hashCode());
System.out.println("b.hashCode() - " + b.hashCode());
System.out.println("a == b - " + (a == b));
System.out.println("a.equals(b) - " + (a.equals(b)));

是不同的:

a.hashCode() - 1627674070
b.hashCode() - 1360875712
a == b - false
a.equals(b) - false

现在我们有两个不同的对象,因为hashCode是不同的,这就是为什么两个条件都是False (它应该是这样)的原因。

感觉我需要填补知识空白,并会欣赏任何指导。

提前致谢!

这里感知的问题在于你对hashCode -method和数组的equals方法的理解。

hashCode方法可以在Object中找到,并将根据对象引用创建一个哈希。

String类使用自己的逻辑基于对Stringchar进行的计算来覆盖此方法(更准确地说,它使用公式s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1]计算哈希值s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1]其中s[i]Stringi个字符)。 这意味着对于彼此equal 2个Strings ,您将始终通过调用hashCode获得相同的结果。

int[]改为使用Object的实现,因此从对象引用创建哈希。 这意味着对于具有相同值的2个数组,您仍然可以通过调用hashCode获得不同的结果。

另外,为了比较两个数组的值,使用Arrays.equals作为调用int[].equals Arrays.equals与使用==运算符相同 - 再次 - 用于参考比较。 Arrays.equals反而在数组中的每个元素上调用equals方法,并根据它们的相等性返回结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM