views:

177

answers:

4

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
+7  A: 

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

OscarRyz
This is the best answer so far (award it). When you are considering implementing Cloneable, or overrideing equals or hashcode please read: http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.htmlMy general-purpose advice: don't use Cloneable/clone() but use a copy constructor (which takes only an instance of the current Class as an argument) to make a copy. Save yourself the pain.
Adriaan Koster
+5  A: 

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"
Michael Myers
+1 for completing the answer. I'm linking you on mine :)
OscarRyz
A: 

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

Pratik Bhatt
+1  A: 

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.

Gaël Marziou