Java中的对象身份与平等

问题描述 投票:3回答:1

请看下面的两个例子:

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(它应该是这样)的原因。

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

提前致谢!

java compare equals hashcode hash-code-uniqueness
1个回答
3
投票

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

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

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.