Java:如何测试数组相等性? [英] Java: How to test on array equality?

查看:30
本文介绍了Java:如何测试数组相等性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码打印"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.");

推荐答案

为什么下面的代码打印Different."?

因为 Arrays.equals 执行比较.由于数组从 Object 继承了它们的 equals 方法,因此将对内部数组执行身份比较,这将失败,因为 ab 不引用 same 数组.

Because Arrays.equals performs a shallow comparison. Since arrays inherit their equals-method from Object, an identity comparison will be performed for the inner arrays, which will fail, since a and b do not refer to the same arrays.

如果更改为 Arrays.deepEquals 它将按预期打印 "Equal.".

这篇关于Java:如何测试数组相等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆