Java Array Copy – Deep Copy and Shallow Copy

Learn to create an array copy in Java. We will learn to shallow copy and deep copy an array with easy-to-follow examples.

1. Creating a Shallow Copy of Array

In shallow copying, the references of the array items are copied into the new array, so any change in the array or the array items is visible on the cloned copied array. The array.clone() method creates a shallow copy.

Let us go through a few methods that create shallow copies of an array in Java.

1.1. Using Object.clone() Method

In Java, to create a clone of an array, we should use array.clone(). It creates a shallow copy of the array. The default cloning always creates a shallow copy of the array. Any change (in the original array) will also be reflected in the cloned array.

Employee[] clonedArray = empArray.clone();

Let us see an example. When we made changes to empArray items, the items in the clonedArray are also changed.

Employee[] empArr = new Employee[2];  //Original array

empArr[0] = new Employee(100, "Lokesh", "Gupta", new Department(1, "HR"));
empArr[1] = new Employee(200, "Pankaj", "Kumar", new Department(2, "Finance"));
 
Employee[] clonedArray = empArray.clone();  //Shallow copied array
 
empArray[0].setFirstName("Unknown");
empArray[0].getDepartment().setName("Unknown");
 
System.out.println(empArray[0].getFirstName());           //Unknown
System.out.println(empArray[0].getDepartment().getName());      //Unknown
 
System.out.println(clonedArray[0].getFirstName());          //Unknown
System.out.println(clonedArray[0].getDepartment().getName());   //Unknown

1.2. Using Arrays.copyOf()

The Arrays.copyOf(array, newLength) method copies the specified array, truncating or padding with default values, so the copies array has the specified newLength.

The copyOf() is an overloaded method, so the default value to be filled in empty places depends on the type of elements in the array. For example, a boolean array will be filled with false and int array will be filled with 0. Object types will be filled with nulls.

Employee[] empArr = new Employee[2];

Employee[] copiedArray = Arrays.copyOf(empArray, empArr.length);  

1.3. Using System.arraycopy()

Another useful method provided by JDK. It is a native method and is also invoked within Arrays.copyOf() method, internally. But it makes code a little less readable due to multiple arguments used for invocation.

The arraycopy() method copies the items from srcArray (starting position srcPos) into destArray (starting position destPos). The count of items to be copied is specified using the length argument.

public static native void arraycopy(Object srcArray,  int  srcPos, Object destArray, int destPos, int length);

In the following example, all items from names array are copied into copyOfNames array, starting from position zero in both arrays.

String[] names = {"Alex", "Brian", "Charles", "David"};
String[] copyOfNames = new String[names.length];

System.arraycopy(names, 0, copyOfNames, 0, copyOfNames.length);
 
System.out.println(Arrays.toString(names));     //[Alex, Brian, Charles, David]
System.out.println(Arrays.toString(copyOfNames));   //[Alex, Brian, Charles, David]

2. Creating a Deep Copy of Array

In deep copying, new instances of the array items are created, so any change to the original array does not reflect on the copied array. In-memory serialization is a shortcut approach for creating deep copies of an object in Java.

If you want to create a deep copy of an array in Java, then use Apache Common’s SerializationUtils.clone( array) method.

Employee[] copiedArray = SerializationUtils.clone(empArray);  //Deep copied array

Let us verify with an example.

Employee[] empArray = new Employee[2];
 
empArray[0] = new Employee(100, "Lokesh", "Gupta", new Department(1, "HR"));
empArray[1] = new Employee(200, "Pankaj", "Kumar", new Department(2, "Finance"));
 
Employee[] copiedArray = SerializationUtils.clone(empArray);  //Deep copied array
 
empArray[0].setFirstName("Unknown");
empArray[0].getDepartment().setName("Unknown");
 
//Verify the change in original array - "CHANGED"
System.out.println(empArray[0].getFirstName());           //Unknown
System.out.println(empArray[0].getDepartment().getName());      //Unknown
 
//Verify the change in deep copied array - "UNCHANGED"
System.out.println(copiedArray[0].getFirstName());          //Lokesh
System.out.println(copiedArray[0].getDepartment().getName());   //HR

Happy Learning !!

Comments

Subscribe
Notify of
guest
4 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode