user1071840
user1071840

Reputation: 3592

Copy arrays of primitive types using System.arrayCopy, is it shallow or deep?

I understand how System.arrayCopy() creates a shallow copy of Object[] arrays that are passed to it.

But I do not understand how does it work on arrays of primitive types such as int[] or byte[]. There are no references to copy. There should not be any difference in shallow or deep copy in this case.

Upvotes: 1

Views: 1373

Answers (2)

Johnyzhub
Johnyzhub

Reputation: 414

System.arrayCopy() on Arrays of primitive types results deep copy.

From your comments: "There should not be any difference in shallow or deep copy in this case"

There is a difference. If the destination array is a shallow copy after the change, the changes you make to the destination array should effect the source array and vice versa. But that is not the case here.

Let me give an example here:

public class ArrayCopy {
public static void main(String args[]) {
    int arr1[] = {0, 1, 2, 3, 4, 5};
    int arr2[] = {10, 11, 12, 13, 14, 15};
    System.out.println("Before change");
    System.out.println("arr1 " + Arrays.toString(arr1));
    System.out.println("arr2 " + Arrays.toString(arr2));
    System.arraycopy(arr1, 0, arr2, 0, 3);
    System.out.println("After change for arr2");
    System.out.println("arr1 " + Arrays.toString(arr1));
    System.out.println("arr2 " + Arrays.toString(arr2));
    int arr3[] = {20, 30};
    System.arraycopy(arr3, 0, arr1, 0, 2);
    System.out.println("After change for arr1");
    System.out.println("arr1 " + Arrays.toString(arr1));
    System.out.println("arr2 " + Arrays.toString(arr2));
}}

     Result:
 Before change
 arr1 [0, 1, 2, 3, 4, 5]
 arr2 [10, 11, 12, 13, 14, 15]
 After change for arr2
 arr1 [0, 1, 2, 3, 4, 5]
 arr2 [0, 1, 2, 13, 14, 15]
 After change for arr1
 arr1 [20, 30, 2, 3, 4, 5]
 arr2 [0, 1, 2, 13, 14, 15]

If you see the result, if it a shallow copy, "After change for arr1" should result

                  arr1 [20, 30, 2, 3, 4, 5]
                  arr2 [20, 30, 2, 13, 14, 15]

But that is not case, because System.arrayCopy results deep copy for primitive types. I hope this answers your question.

Upvotes: 0

Mureinik
Mureinik

Reputation: 311853

As you noted:

There are no references to copy. There should not be any difference in shallow or deep copy in this case.

For primitives, System.arrayCopy just copies the values of the array's elements.

Upvotes: 2

Related Questions