6

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();
}
}
eagertoLearn
  • 9,772
  • 23
  • 80
  • 122
  • this article is related, but does not explain if system.arraycopy is a deep cloning. It DOES mention that clone create a shallow copy and the examples there illustrates it. but to know if system.arraycopy is deep cloning with an illustration would be useful for beginners in Java – eagertoLearn Sep 12 '13 at 18:47
  • System.arraycopy() does what it says in the Javadoc, nothing more, no deep copy. – user207421 Sep 13 '13 at 03:01

1 Answers1

12

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
Jean Waghetti
  • 4,711
  • 1
  • 18
  • 28