Java:clone()和相等性检查 [英] Java: clone() and equality checks

查看:56
本文介绍了Java:clone()和相等性检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我不明白 clone()的工作方式。返回值不等于调用者吗?

Perhaps I don't understand how clone() works. Shouldn't the return value equal the caller?

int[] nums = new int[] {0, 1, 2};
int[] list = nums.clone();
nums.equals(list); //returns false. Why?

for (int ket = 0; ket < list.length; ket++) {

       System.out.println(list[ket] == nums[ket]); //prints out true every time
}

list == nums //false


推荐答案

因为数组的equals实现与Object相同,所以

Because the equals implementation of array is the same as Object which is

public boolean equals( Object o ) { 
   return this == o;
}

参见此问题

See this also this question

在两种情况下,这都是错误的。原始对象和副本的引用值是两个不同的对象(具有相同的值,但对象引用仍然不同)。

and in both cases you tested, that's false. The reference values of the original and the copy are two different objects (with the same value but still different object references).

clone方法的作用是创建一个副本给定的对象。创建新对象时,其引用与原始对象不同。这就是为什么等于 == 产生假的原因。

What the clone method does is create a copy of the given object. When the new object is created, its reference is different from the original. That's why equals and == yield false.

如果要测试两个数组是否相等,请在此处执行以下操作: Arrays.equals()

If you want to test for equality two arrays, do as mmyers here: Arrays.equals():

这篇关于Java:clone()和相等性检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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