开发者

Java: clone() and equality checks

Perhaps I don't understand how clone() wo开发者_StackOverflow中文版rks. 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


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


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"


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜