Java Copy Arrays



In this tutorial, we will learn about different ways to use to copy arrays in Java with the help of examples.

In Java, there are several ways to copy an array into another.


Copying Arrays Using Assignment Operator

Let us consider the following example using the assignment operator = to copy an array.

class Main {
    public static void main(String[] args) {
        int [] numbs = {1, 2, 3, 4, 5};
        int [] arrayNumbs = numbs;  // copying arrays

        for (int numb: arrayNumbs) {
            System.out.print(numb + ", ");
        }
    }
}

Output:

1, 2, 3, 4, 5, 

In the above example, we have used the assignment operator = to copy an array name numbs to another array arrayNumbs.

The assignment operator = technique is the easiest way to copy an array. However, there is a problem with this technique. If we change an element of one array, the corresponding elements of the other arrays also change. For example,

class Main {
    public static void main(String[] args) {
        int [] numbs = {1, 2, 3, 4, 5};
        int [] anotherNumbs = numbs;  // copying arrays
        
        // change value of the second array
        numbs[1] = -2;
        
        for (int numb: arrayNumbs) {
            System.out.print(numb + ", ");
        }
    }
}

Output:

1, -2, 3, 4, 5, 

As we can see above, when we have changed one value of the numbs array. The same value on the anotherNumbs array has also changed.

The explication is because both arrays refer to the same array object. When using the assignment operator = to copy an array is a shallow copy that will copy just the reference so both the array variables will reference the same place in memory.

Note

  • When using the assignment operator = to copy an array, it will just copy the reference of this array. So it's not a real copy. It's just a shallow copy.

Now, to make a new array object while copying the array, we need to use a deep copy rather than a shallow copy.


Using a Loop Construct to Copy Array

In the following example, we will use the for loop to iterate through an array. In each iteration, we will copy elements from one array to another.

import java.util.Arrays;

class Main {
    public static void main(String[] args) {
        int []  src = {1 , 2, 3, 4, 5};
        int [] dest = new int[5];

        // iterate and copy elements from src to dest
        for(int i = 0; i < src.length; i++) {
            dest[i] = src[i];
        }
        
        // displaying the dest array by converting it to string 
        System.out.println(Arrays.toString(dest));
    }    
}

Output:

[1, 2, 3, 4, 5]

Here above, the src and dest array refer to different objects (deep copy). So if there is some change in elements of one array, the corresponding elements of the other array don't change.

We also used the toString() method to convert an array into a string.


Copying Arrays Using arraycopy() method

In Java, the java.lang.System class provides a method named arraycopy() to copy arrays. This method is a better approach for copying arrays than other approaches we already explained above.

The arraycopy() method is used to copy a specified portion of the source array to the destination array. For example,

arraycopy(Object sourceArr, int sourcePos, Object destArr, int destPos, int len)

Here,

  • sourceArr - array to be copied from
  • sourcePos - starting position in source array from where to copy
  • destArr - array to be copied in
  • destPos - starting position in destination array, where to copy in
  • len - number of elements to copy

In the following example, we will use the arraycopy() method to copy arrays.

import java.util.Arrays;

class Main {
    public static void main(String[] args) {
        int[] t1 = {1, 2, 3, 4, 5, 6};
        
        int[] t2 = new int[t1.length];

        int[] t3 = new int[4];

        // copying entire t2 array to t2 
        System.arraycopy(t1, 0, t2, 0, t1.length);
        System.out.println("t2 = " + Arrays.toString(t2));

        // copying elements from index 1 on t1 array
        // copying elements to index 1 of t3 array
        System.arraycopy(t1, 1, t3, 1, 2);
        System.out.println("t3 = " + Arrays.toString(t3));
    }

}

Output:

t2 = [1, 2, 3, 4, 5, 6]
t3 = [0, 2, 3, 0]

In the above example, we have used the arraycopy() method to:

  • System.arraycopy(t1, 0, t2, 0, t1.length) - copy entire elements from the t1 into the t2 array.
  • System.arraycopy(t1, 1, t3, 1, 2) - 2 elements of the t1 array starting from index 1 are copied to the index starting from 1 of the t3 array.

As you already know, the initial default value of elements of an int type array is 0.


Copying Arrays Using copyOfRange() method

In Java, the java.util.Arrays class provides a method named copyOfRange() used to copy elements within a specified range of the original array.

Let's take an example,

import java.util.Arrays; 

class Main {
    public static void main(String[] args) {
        int[] src = {1, 2, 3, 4, 5};
        
        // copying entire src array to dest1
        int[] dest1 = Arrays.copyOfRange(src, 0, src.length);
        System.out.println("dest1 = " + Arrays.toString(dest1));

        // copying from index 1 to 4 (4 is not included)
        int[] dest2 = Arrays.copyOfRange(src, 1, 4);
        System.out.println("dest2 = " + Arrays.toString(dest2));
    }
}

Output:

dest1 = [1, 2, 3, 4, 5]
dest2 = [2, 3, 4]

In the above example, we can see the following line:

int[] dest1 = Arrays.copyOfRange(src, 0, src.length);

Here, we can notice that we are creating the dest1 array and copying the src array to it simultaneously. As we can see, we are not creating the dest1 array before calling the copyOfOrange() method.


Copying 2d Arrays Using Loop

Similar to the single-dimensional array, we can also use a for loop. For example,

import java.util.Arrays; 

class Main {
    public static void main(String[] args) {

        int[][] src = {
            {1, 2, 3},
            {4, 5},
            {6, 7, 8, 9}
        };

        int[][] dest = new int[src.length][];

        for (int i = 0; i < dest.length; i++) {
            // allocating space for each row of destination array
            dest[i] = new int[src[i].length];

            for(int j = 0; j < dest[i].length; j++) {
                dest[i][j] = src[i][j];
            }
        }

        // Printing dest array
        System.out.println(Arrays.deepToString(dest));
    }
}

Output:

[[1, 2, 3], [4, 5], [6, 7, 8, 9]]

Here above, we used the deepToString() method to provide a better representation of the 2-dimensional array.


Copying 2d Arrays using arraycopy()

We can also use the System.arraycopy() method that makes it simpler to copy a 2-dimensional array.

Let's consider the following example,

import java.util.Arrays;

class Main {
    public static void main(String[] args) {

        int[][] src = {
            {1, 2, 3},
            {4, 5},
            {6, 7, 8, 9}
        };

        int[][] dest = new int[src.length][];

        for (int i = 0; i < src.length; i++) {
            
            // allocating memory space for each row of dest array
            dest[i] = new int[src[i].length];
            System.arraycopy(src[i], 0, dest[i], 0, dest[i].length);
        }

        // Printing dest array
        System.out.println(Arrays.deepToString(dest));
    }
}

Output:

[[1, 2, 3], [4, 5], [6, 7, 8, 9]]

As we can see above, we get the same output by replacing the inner for loop with the arraycopy() method.



ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.