gpt4 book ai didi

java - 数组的 equal 方法如何工作?

转载 作者:搜寻专家 更新时间:2023-10-31 08:07:57 24 4
gpt4 key购买 nike

嘿,我目前正在学习 Java 期末考试,我对一个简单的 equals 方法感到困惑。

给出的问题是

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

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

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

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

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 中的默认实现,即引用相等。

对于数组中的值相等(即相同顺序的相等元素),使用 Arrays 中的静态方法类。

关于java - 数组的 equal 方法如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8392771/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com