home > tutorial > java

Duplicating Arrays in Java - Don't Fall for the Shallow Trap!_

We have all been there, we create an array arr1 and then decide to create a new array called arr2 so we execute the following in Java:

arr2 = arr1;

Unfortunately, after changing values in arr1 we notice that values in arr2 are also changing. This is called aliasing and has given many Hacker novices sleepless nights. Aliasing is a situation in which a data location in memory can be accessed through different symbolic names in the program. So arr1 and arr2 point to the same address on your computer - you can think of them as being two pieces of paper with the same house address. They point to the same data so when you change that data by indexing into arr1 and arr2, both arrays will be affected.

So what’s the solution to aliasing?

The solution is to create a deep copy of arr1 and place its reference in arr2 i.e. create a new array of arr2 and duplicate the values in arr1 into the new array.

Using Arrays

The Arrays class provides useful methods to operate on arrays and one of them is copyOf. We can use copyOf to create a deep copy of arr1 and store its reference in arr2.

Code

import java.util.Arrays;

public class ArrayCopy {
    public static void main(String[] args) {
        int[] arr1 = {11, -1, 12, 27, 0};
        int n = arr1.length;
        int[] arr2 = Arrays.copyOf(arr1, n);

        arr1[0] = 55;
        arr1[3] = 33;
        // print arr1
        System.out.print("arr1: ");
        for (int i = 0; i < arr1.length; i++) {
            System.out.print(arr1[i] + " ");
        }
        System.out.println();
        // print arr2
        System.out.print("arr2: ");
        for (int j = 0; j < arr2.length; j++) {
            System.out.print(arr2[j] + " ");
        }
        System.out.println();
    }
}

Output

arr1: 55 -1 12 33 0 
arr2: 11 -1 12 27 0

Using System

The System class contains several useful class fields and methods.

Among the facilities provided by the System class are standard input, standard output, and error output streams; access to externally defined properties and environment variables; a means of loading files and libraries; and a utility method for quickly copying a portion of an array.

The arraycopy() static method in the System class copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. So we can use arr1 as the source array and arr2 is the destination array. Since we want arr2 to be a duplicate of arr1 we can specify 0 as the starting point for the copying process.

Code

public class ArrayCopy2 {
    public static void main(String[] args) {
        int[] arr1 = {11, -1, 12, 27, 0};
        int[] arr2 = new int[arr1.length];
        // run the copy method
        System.arraycopy(arr1, 0, arr2, 0, arr1.length);

        arr1[0] = 55;
        arr1[3] = 33;
        // print arr1
        System.out.print("arr1: ");
        for (int i = 0; i < arr1.length; i++) {
            System.out.print(arr1[i] + " ");
        }
        System.out.println();
        // print arr2
        System.out.print("arr2: ");
        for (int j = 0; j < arr2.length; j++) {
            System.out.print(arr2[j] + " ");
        }
        System.out.println();
    }
}

Output

arr1: 55 -1 12 33 0 
arr2: 11 -1 12 27 0

Another approach: make your own

It’s not a Hacker Bytes blog if we don’t consider creating a custom solution. Let's consider creating a new array for arr2 with the same length as arr1. Then we iterate all the values in arr1 and copy them into arr2

Code

public class ArrayCopy3 {
    public static void main(String[] args) {
        int[] arr1 = {11, -1, 12, 27, 0};
        // create a new array for arr2
        int[] arr2 = new int[arr1.length];
        // populate the values in arr1 into arr2
        // i.e. we make copies of the values
        for (int i = 0; i < arr1.length; i++) {
             arr2[i] =  arr1[i];
        }

        arr1[0] = 55;
        arr1[3] = 33;
        // print arr1
        System.out.print("arr1: ");
        for (int j = 0; j < arr1.length; j++) {
            System.out.print(arr1[j] + " ");
        }
        System.out.println();
        // print arr2
        System.out.print("arr2: ");
        for (int k = 0; k < arr2.length; k++) {
            System.out.print(arr2[k] + " ");
        }
        System.out.println();
    }
}

By using arr2[i] = arr1[i] we complete the array duplication process in the first for loop.

Output

arr1: 55 -1 12 33 0 
arr2: 11 -1 12 27 0

table of contents

Ready to join the movement?

Dive into our articles, explore our resources, and join the clan. Together, let's rewrite the rules of coding education and prove that learning can be fun, effective, and a little bit rebellious.

Subscribe to receive updates about new posts.