问题描述
也许我不明白 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;
}
在两种情况下,这都是错误的。原始对象和副本的引用值是两个不同的对象(具有相同的值,但对象引用仍然不同)。
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.
如果要测试两个数组是否相等,请在此处执行以下操作::
If you want to test for equality two arrays, do as mmyers here: Arrays.equals():
这篇关于Java:clone()和相等性检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!