Copying an Array

In this lesson, we explore how to make a duplicate copy of an array.

Sometimes we must make a distinct copy of an array. Perhaps we want to modify the contents of an array but retain the original data. By first copying the array, we can make our changes to the copy and still have the original version. At other times, an algorithm might require us to copy all or part of an array to another array. We can perform such tasks in one of several ways.

Our first techniques can create duplicate arrays, such as the duplicate arrays of integers pictured below.

Duplicate arrays of integers
Duplicate arrays of integers

Using a loop

Given an existing array that already contains values, we create a second array of the same length and data type as the existing array. We then can copy each value in the first array to a corresponding element in the new array, as in the following example:

Press + to interact
Java
public class Example
{
public static void main( String args[] )
{
int[] data = {2, 4, 6, 8, 10, 12, 14, 18, 20};
int[] copyOfData = new int[data.length];
// Copy the array
for (int index = 0; index < data.length; index++)
copyOfData[index] = data[index];
// Display the results
System.out.println("The original array:");
for (int index = 0; index < data.length; index++)
System.out.print(data[index] + ", ");
System.out.println();
System.out.println("\nThe copy:");
for (int index = 0; index < data.length; index++)
System.out.print(copyOfData[index] + ", ");
System.out.println();
} // End main
} // End Example

Although this code is not difficult to write, faster and easier ways to copy an array are possible, as we will now see.

Using the method System.arraycopy

We have used the class System from the Java Class Library when we performed input and output, likely without thinking much about it. This class defines several static methods, among which is arraycopy. We can use this method instead of the loop that we wrote in the previous segment to copy values from one array to another, as follows:

Press + to interact
Java
public class Example
{
public static void main( String args[] )
{
int[] data = {2, 4, 6, 8, 10, 12, 14, 18, 20};
int[] copyOfData = new int[data.length];
// Copy the array
System.arraycopy(data, 0, copyOfData, 0, data.length);
// Display the results
System.out.println("The original array:");
for (int index = 0; index < data.length; index++)
System.out.print(data[index] + ", ");
System.out.println();
System.out.println("\nThe copy:");
for (int index = 0; index < data.length; index++)
System.out.print(copyOfData[index] + ", ");
System.out.println();
} // End main
} // End Example

Notice that we must declare and allocate the array copyOfData before we call arraycopy, but the array need not contain specific values. The second argument—0—in the call to arraycopy is the index of the first element in the original array, data, to be copied. The fourth argument—0—is the index of the first element in copyOfData to be given a value. The last argument is the number of values to be copied.

Since the class System is in the package java.lang and is included automatically in every Java program, no import statement is needed when you use System.arraycopy. Note that arraycopy is entirely lowercase.

📝 Syntax: The method System.arraycopy

public static void arraycopy(Object sourceArray, int sourceIndex,
                             Object destinationArray, int destIndex, int count)

The method copies all or a part of a given array to a specified destination array. In particular, it copies count consecutive values from the array sourceArray, beginning at sourceIndex, to consecutive elements in the array destinationArray, beginning at destIndex.

The method can move a portion of an array to another part of the same array. That is, if sourceArray and destinationArray reference the same array, the result is the same as if values from sourceArray were first copied to a temporary array and then copied from the temporary array into destinationArray.

Question 1

Given the arrays data and copyOfData, as the following statements define, what call to arraycopy will copy the integers 6, 8, 10, 12, and 14 from data to the portion of copyOfData that begins at index 0?

int[] data = {2, 4, 6, 8, 10, 12, 14, 18, 20};
int[] copyOfData = new int[data.length];

0/500
Show Answer
1 of 4
Press + to interact
Java
public class CheckpointQuestions
{
public static void main( String args[] )
{
int[] data = {2, 4, 6, 8, 10, 12, 14, 18, 20};
int[] copyOfData = new int[data.length];
// Write your answers here:
} // End main
} // End CheckpointQuestions

Using the method Arrays.copyOf

The class Arrays in the package java.util of the Java Class Library defines several static methods that manipulate arrays. In particular, the method copyOf returns a copy of a given array. For example, the following statements define an array data and then make a duplicate copy of it:

int[] data = {2, 4, 6, 8, 10, 12, 14, 18, 20};
int[] copyOfData = Arrays.copyOf(data, data.length);

These two arrays have the same length and contents.

If we replace the second argument in the previous example with a value that is less than data’s length, fewer values are copied from data, and the size of the returned array is reduced accordingly. For example:

int[] data = {2, 4, 6, 8, 10, 12, 14, 18, 20};
int[] copyOfData = Arrays.copyOf(data, 3);

copies 2, 4, and 6 into copyOfData so that copyOfData.length is 3.

On the other hand, if the second argument given to copyOf is larger than data.length, the size of the returned array will be larger than the size of the given array. Elements after the one containing the last value copied from the given array will contain either zero, false, or null, according to the data type of the array’s entries. For example,

int[] data = {2, 4, 6};
int[] copyOfData = Arrays.copyOf(data, 7);
// copyOfData contains 2, 4, 6, 0, 0, 0, 0

copies 2, 4, and 6 into the seven-element array copyOfData so that entries after 6 are zero, and copyOfData.length is 7.

📝 Syntax: The method Arrays.copyOf

The standard class Arrays in the package java.util of the Java Class Library defines several static methods, each named copyOf. Each of these methods returns a new array of a given length and data type containing values copied from a given array.

public static entry_type[] copyOf(entry_type[] sourceArray, int newLength) 

The method returns a new array of length newLength containing values copied from consecutive values in the array sourceArray. If newLength > sourceArray.length, the additional elements in the returned array are given values of zero, false, or null, as appropriate for the data type of the array. If newLength < sourceArray.length, the additional values in sourceArray are ignored.

Note that entry_type is any data type.

An import statement is necessary when you use Arrays.copyOf in a program.

📝 Note: The method Arrays.copyOf versus System.arraycopy

System.arraycopy was included in the original version of Java. The method copyOf was added to the class Arrays later in a revision of Java. You can copy an array by using either method, as they both copy an array faster than you could using a loop.

  • Before calling System.arraycopy, you must allocate an array to hold the copy.
  • Arrays.copyOf, however, does this step for you, and so it is preferable to arraycopy.

Copying arrays of objects

An array of primitive values actually contains those values. When we copy primitive values from one variable or array to another, duplicate values are created. Such is the case when we duplicate an array of integers, as we saw at the beginning of this lesson. However, an array of objects contains only references to the objects, not the objects themselves. For example, here is an illustration of an array of strings:

Thus, copying such an array copies the references.

Duplicating this array of strings using any of the techniques we have just introduced would give us two distinct arrays of references to the strings. That is, the references would be copied from one array to the other. Thus, we would have only one set of strings, as the figure given below shows. This copy of the array is called a shallow copy.

If we were to duplicate both the strings and the array of references, the original array, and the duplicate array would each reference their own set of strings, as the figure given below illustrates. The duplicate is called a deep copy.

Since any string, once created, cannot be altered, sharing it causes no problems. Thus, a shallow copy of an array of strings is perfectly acceptable. But when the objects in an array can be modified—perhaps by a set method—we should create a deep copy.