To copy the contents of one array into another, you have to copy the array’s individual elements into the other array. Often, in a program, you need to duplicate an array or a part of an array. In such cases you could attempt to use the assignment statement (=), as follows:
list2 = list1;
However, this statement does not copy the contents of the array referenced by list1 to list2, but instead merely copies the reference value from list1 to list2. After this statement, list1 and list2 reference the same array, as shown below. The array previously referenced by list2 is no longer referenced; it becomes garbage, which will be automatically collected by the Java Virtual Machine (this process is called garbage collection).
In Java, you can use assignment statements to copy primitive data type variables, but not arrays. Assigning one array variable to another array variable actually copies one reference to another and makes both variables point to the same memory location. There are three ways to copy arrays:
- Use a loop to copy individual elements one by one.
- Use the static arraycopy method in the System class.
- Use the clone method to copy arrays
You can write a loop to copy every element from the source array to the corresponding element in the target array. The following code, for instance, copies sourceArray to targetArray using a for loop.
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
for (int i = 0; i < sourceArray.length; i++) {
targetArray[i] = sourceArray[i];
}
Another approach is to use the arraycopy method in the java.lang.System class to copy arrays instead of using a loop. The syntax for arraycopy is:
arraycopy(sourceArray, srcPos, targetArray, tarPos, length);
The parameters srcPos and tarPos indicate the starting positions in sourceArray and targetArray, respectively. The number of elements copied from sourceArray to targetArray is indicated by length. For example, you can rewrite the loop using the following statement:
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
The arraycopy method does not allocate memory space for the target array. The target array must have already been created with its memory space allocated. After the copying takes place, targetArray and sourceArray have the same content but independent memory locations. The arraycopy method violates the Java naming convention. By convention, this method should be named arrayCopy (i.e., with an uppercase C).
Top comments (1)
Nice explanation, could be good to have a clone example.