数组的平等方法如何工作? [英] How does an array's equal method work?

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

问题描述

嘿,我正在学习Java决赛,我被一个简单的等于方法弄糊涂了。

Hey I'm currently studying for a java final and I am befuddled by a simple equals method.

给出的问题是


鉴于以下数组声明,什么做以下打印

"Given the following array declarations, what does the following print"

我认为这是真的,假的,但是在复制并粘贴代码之后它会显示答案是虚假,虚假,真实。

and I thought it would be true, false, true however after copy and pasting the code it reveals the answer is false, false, true.

我知道 == 只有当它们是对象的同一个实例但我不明白时才有用为什么第一个是假的。我尝试在数组api中找到该方法,但找不到具有相同参数的方法。

I understand that the == only works when they are the same instance of the object but I do not understand why the first on is false. I tried finding the method in the array api but could not find one with the same arguments.

请原谅我,如果这是显而易见的,我在学习过去的几个晚上一直很晚,而且现在对咖啡因感到厌倦。

Forgive me if this is obvious, I've been up late the past couple nights studying and am quite jaded on caffeine at the moment.

int[] d = { 1, 2, 3 };
int[] b = { 1, 2, 3 };
int[] c = d;
System.out.println(d.equals(b));
System.out.println(d == b);
System.out.println(d == c);


推荐答案

基本上,数组类型不会覆盖 equals 提供值相等...所以你最终得到了Object中的默认实现,它是引用相等。

Basically, array types don't override equals to provide value equality... so you end up with the default implementation in Object, which is reference equality.

For数组中的值相等(即相同顺序的相等元素),使用 数组 class。

For value equality in arrays (i.e. equal elements in the same order), use the static methods in the Arrays class.

这篇关于数组的平等方法如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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