What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

Apr 29 2010 8:29 AM

The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.
Here is a short example with Integer:
int [] numbers = { 2, 3, 4, 5}; 
int [] numbersCopy = numbers; 
numbersCopy[2] = 0; 
System.out.println(numbers[2]);//Display 0 
System.out.println(numbersCopy[2]);//Display 0 !!! Both = Same reference 

But if you do :
int [] numbers = { 2, 3, 4, 5}; 
int [] numbersClone = (int[])numbers.clone(); 
numbersClone[2] = 0; 
System.out.println(numbers[2]);//Display 4 
System.out.println(numbersClone[2]);//Display 0 !!! Not the same :) 

Hash code of an object is the same with a copy array, when cloning is not.

Answers (2)