Java: clone() and equality checks

匆匆过客 提交于 2019-12-10 09:59:10

问题


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

回答1:


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).

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():




回答2:


Oscar Reyes has the correct answer. I'll just add that Arrays.equals() does exactly the sort of equality comparison that you're looking for.

int[] nums = new int[] {0, 1, 2};
int[] list = nums.clone();
System.out.println(Arrays.equals(nums, list)); // prints "true"



回答3:


Have a look at the javadoc for Objet.clone(), it clearly states that while it is typically the case that: "x.clone().equals(x)" will be true, this is not an absolute requirement.




回答4:


because num.equals doesnt check for the equality of the elements, but it checks whether the two variables point to the same object. In your case, although the elements are the same, but nums and lists point to two different objects.

you could use java.util.Arrays.equals(...) function to do the comparison.

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#equals%28int[],%20int[]%29




回答5:


nums.equals(list); //false

list == nums; //false

Reason : By default equals() will behave the same as the “==” operator and compare object locations. here nums and list have different memory locations.

/* But, equals method is actually meant to compare the contents of 2 objects, and not their location in memory. So for accomplishing it you can override equals() method. */

list[ket] == nums[ket] //True

The clone is a shallow copy of the array. So, both refers same memory locations. hence it returns true



来源:https://stackoverflow.com/questions/1574960/java-clone-and-equality-checks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!