Search code examples
javaarrayscopyclone

clone vs copying Array in Java?


I have this bit of code, where I am making a copy of an array. using System.arraycopy seems more verbose than clone(). but both give the same results. are there any advantages of one over the other? here is the code:

import java.util.*;
public class CopyArrayandArrayList {
    public static void main(String[] args){
        //Array copying
    char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e'};
    char[] copyTo = new char[7];

    System.arraycopy(copyFrom, 0, copyTo, 0, 7);

    char[] copyThree = new char[7];
    copyThree=copyFrom.clone();
}
}

Solution

  • The object you created with:

    char[] copyThree = new char[7];
    

    will be gc'd. The "final result" could be achieved with:

    char[] copyThree = copyFrom.clone();
    

    Using System.arrayCopy, copyFrom and copyTo need to meet certain requirements, like array types and size of the array.

    Using the clone method, a new array will be created, with the same contents of the other array (same objects - the same reference, not different objects with same contents). Of course the array type should be the same.

    Both ways copy references of the array contents. They not clone the objects:

    Object[] array = new Object[] {
        new Object(),
        new Object(),
        new Object(),
        new Object()};
    Object[] otherArray = new Object[array.length];
    Object[] clonedArray = array.clone();
    
    System.arraycopy(array, 0, otherArray, 0, array.length);
    
    for (int ii=0; ii<array.length; ii++) {
    
        System.out.println(array[ii]+" : "+otherArray[ii]+" : "+clonedArray[ii]);
    
    }
    

    Provides:

    java.lang.Object@1d256a73 : java.lang.Object@1d256a73 : java.lang.Object@1d256a73
    java.lang.Object@36fb2f8 : java.lang.Object@36fb2f8 : java.lang.Object@36fb2f8
    java.lang.Object@1a4eb98b : java.lang.Object@1a4eb98b : java.lang.Object@1a4eb98b
    java.lang.Object@2677622b : java.lang.Object@2677622b : java.lang.Object@2677622b