This post will discuss how to copy an object array into a new array in Java.

We have discussed how to copy a primitive array into a new array in Java in the previous post. This post will discuss how we can copy an object array.

1. Using System.arraycopy() method

System.arraycopy() simply copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. If the source array contains reference elements, they are also copied.

Download  Run Code

Output:

Copied successfully: [1, 2, 3, 4, 5]

 
The above code is equivalent to:

Download  Run Code

2. Using Object.clone() method

We know that arrays are objects in Java, and all methods of the Object class may be invoked on an array.

Object class has clone() method for copying objects in Java, and since arrays are treated as objects, we can use this method for copying arrays as well.

Download  Run Code

Output:

Copied successfully: [1, 2, 3, 4, 5]

 
Please note that the Object.clone() method creates a shallow copy of the array, i.e., the new array can reference the same elements as the original array. To illustrate, consider the following example:

Download  Run Code

Output:

Shallow copy

3. Using Arrays.copyOf() method

Arrays.copyOf() can also be used to copy the specified array into a new array, as shown below. If the specified array contains any reference elements, this method also performs a shallow copy.

Download  Run Code

Arrays.copyOf() has an overloaded version where we can specify the Type of the resulting array.

Download  Run Code

4. Using Arrays.copyOfRange() method

Arrays also provides the copyOfRange() method, which is similar to copyOf() but only copies elements between the specified range into a new array.

Download  Run Code

 
Similar to Arrays.copyOf(), a shallow copy of the original array is created, and it also has an overloaded version where we can specify the Type of the resulting array.

5. Serialization of object array using GSON

We have seen that in all approaches discussed above, a shallow copy of the array is created, but this is something we might not want. One simple solution to this problem is Serialization. To illustrate, the following code returns a deep copy of an array by serializing the array with Google’s Gson library.

Download Code

Output:

Deep copy

That’s all about copying an object array in Java.