System.arraycopy() method

When using this method and copying the source array into the destination array, will then the destination array be the same reference as the source array, or it will be a deep copy of the source array?
[215 byte] By [ogorovoy] at [2007-9-26 8:31:56]
# 1
System.arraycopy makes a shallow copy. If you copy an array of references, it is the references that are copied, not the objects themselves. This makes sense, because the array elements are references.If you want a deep copy of an array, you must write a loop to do it.
schapel at 2007-7-1 19:12:45 > top of Java-index,Core,Core APIs...
# 2

Arraycopy will copy the elements in the array. Meaning it will copy the value of the elements. If these elements are references to objects then the reference will be copied and the new element will point to the same object as the old. This is how everything works in Java. What you are asking is whether this will do a deep clone of the objects refernce in the array. The answer is no. Here is a sample program that demonstrates this:

public class Test {

public static void main(String args[]) {

String array1[] = {new String("a"), new String("b")};

String array2[] = new String[2];

System.arraycopy(array1, 0, array2, 0, 2);

for (int i = 0; i < array1.length; i++) {

System.out.println("element at " + i + " " + array1[i] + " " + array2[i]);

System.out.println("elements equal? " + (array1[i] == array2[i]));

}

}

}

dubwai at 2007-7-1 19:12:45 > top of Java-index,Core,Core APIs...
# 3
So, what will happen if I make a shallow copy of an array and then sort it or rearrange its elements?Will it affect the source array in any way?
ogorovoy at 2007-7-1 19:12:45 > top of Java-index,Core,Core APIs...
# 4

No. The copy of the array and the elements is truly a copy. If I could draw in this forum, I would make a box for each object and draw arrows from the references to the objects that they point to. If you draw this diagram for the references to the arrays, the array objects, the references which are elements in the arrays, and the objects to which the references in the arrays point to, you'll understand completely.

schapel at 2007-7-1 19:12:45 > top of Java-index,Core,Core APIs...