Copy an Object Array in Java

In this post, we will see how to copy an Object array into a new array in Java.

 
In the previous post, we have discussed how to copy a primitive array into a new array in Java. In this post, we will see how we can copy an Object array.

 

1. System.arraycopy()

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]

 
Above code is equivalent to:

Download   Run Code

 

2. Object.clone()

We know that arrays are objects in Java and all methods of 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 below example:

Download   Run Code

Output:

Shallow copy

 

3. Arrays.copyOf()

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 resulting array.

Download   Run Code

 

4. Arrays.copyOfRange()

Arrays also provides 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 original array is created and it also has an overloaded version where we can specify the Type of resulting array.

 

5. Serialization of Object Array using GSON

We have seen that in all approaches discussed above, a shallow copy of 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 the help of Google’s Gson Library.

Download

Output:

Deep copy

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz