Java:如何测试数组相等性?
为什么下面的代码打印“Different.”
?
boolean[][] a = { {false,true}, {true,false} };
boolean[][] b = { {false,true}, {true,false} };
if (Arrays.equals(a, b) || a == b)
System.out.println("Equal.");
else
System.out.println("Different.");
Why is the following code printing "Different."
?
boolean[][] a = { {false,true}, {true,false} };
boolean[][] b = { {false,true}, {true,false} };
if (Arrays.equals(a, b) || a == b)
System.out.println("Equal.");
else
System.out.println("Different.");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为
Arrays.equals
执行浅 比较。由于数组从Object
继承其equals
方法,因此将对内部数组执行身份比较,这将失败,因为a
和 < code>b 不引用相同数组。如果更改为
Arrays.deepEquals
它将按预期打印"Equal."
。Because
Arrays.equals
performs a shallow comparison. Since arrays inherit theirequals
-method fromObject
, an identity comparison will be performed for the inner arrays, which will fail, sincea
andb
do not refer to the same arrays.If you change to
Arrays.deepEquals
it will print"Equal."
as expected.这确实不明显。
首先,
==
运算符只是比较两个指针。由于a
和b
是位于不同内存地址的不同对象,因此a == b
将返回false
(嘿,Java 纯粹主义者,我知道==
实际上是比较对象身份,我只是想说教一下。现在让我们看一下数组的 equals() 实现:
这会打印
Not equals
因为没有数组实例实际实现equals()
方法。因此,当我们调用.equals()
时,我们实际上是在调用Object.equals()
方法,该方法只是比较两个指针。也就是说,请注意您的代码实际上是这样做的:
Arrays.equals(a, b)
最终将调用a0.equals(b0)
,它将返回假
。因此,Arrays.equals(a, b)
也将返回false
。因此,您的代码将打印
Different.
,我们得出结论,Java 相等性有时可能很棘手。It's really not obvious.
First of all, the
==
operator just compare two pointers. Becausea
andb
are distinct objects located at different memory addresses,a == b
will returnfalse
(Hey, Java purists, I know that the==
actually compare object identities. I'm just trying to be didactic).Now let's take a look at the
equals()
implementation of arrays:That would print
Not equals
because no array instance actually implements theequals()
method. So, when we call<somearray>.equals(<otherarray>)
we are actually calling theObject.equals()
method, which just compare two pointers.That said, notice that your code is actually doing this:
The
Arrays.equals(a, b)
will eventually calla0.equals(b0)
which will returnfalse
. For this reason,Arrays.equals(a, b)
will returnfalse
as well.So your code will print
Different.
and we conclude that Java equality can be tricky sometimes.对多维数组使用 Arrays.deepEquals()。
Use Arrays.deepEquals() for multidimensional arrays.