What’s the difference between the System.Array.CopyTo()
and System.Array.Clone()
?
views:
3084answers:
6The 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.
Both perform shallow copies as Daok said (Despite the many misled souls who think that CopyTo does a deep copy).
However, CopyTo allows you to copy one array to a specified indice in the destination array, giving it significantly more flexibility.
One other difference not mentioned so far is that
- with
Clone()
the destination array need not exist yet since a new one is created from scratch. - with
CopyTo()
not only does the destination array need to already exist, it needs to be large enough to hold all the elements in the source array from the index you specify as the destination.
object[] myarray = new object[] { "one", 2, "three", 4, "really big number", 2324573984927361 };
//create shallow copy by CopyTo
//You have to instantiate your new array first
object[] myarray2 = new object[myarray.Length];
//but then you can specify how many members of original array you would like to copy
myarray.CopyTo(myarray2, 0);
//create shallow copy by Clone
object[] myarray1;
//here you don't need to instantiate array,
//but all elements of the original array will be copied
myarray1 = myarray.Clone() as object[];
//if not sure that we create a shalow copy lets test it
myarray[0] = 0;
Console.WriteLine(myarray[0]);// print 0
Console.WriteLine(myarray1[0]);//print "one"
Console.WriteLine(myarray2[0]);//print "one"
mgznet.com/CopyToVSClone.aspx
clone()-it is used to copy only structure of data/array it dosn't copy the actual data. copy()-it copy the structure as well as actual data.