2

I first cloned 1D primitive array(It will hold wrappers) and then changed first value of the cloned array. But the first value of the original array was not changed. Then I cloned a 2D array and did the same.(changed the array[0][0] value).There the value was at originalArray[0][0] also was changed. Why this is happening. Is this due to shallow copy and deep copy?

My 1D array example

    int[] arr=new int[2];
    arr[0]=1;
    arr[1]=2;

    int[]arrnew=arr.clone();
    System.out.println(arr[0]);
    System.out.println(arrnew[0]);
    arr[0]=5;
    System.out.println(arr[0]);
    System.out.println(arrnew[0]);

My 2D array example

        int[][] arr=new int[2][2];
        arr[0][0]=1;
        arr[0][1]=2;
        arr[1][0]=3;
        arr[1][1]=4;
        int[][] arrnew=arr.clone();
        System.out.println(arr[1][0]);
        System.out.println(arrnew[1][0]);
        arr[1][0]=5;
        System.out.println(arr[1][0]);
        System.out.println(arrnew[1][0]); 
Sanjaya Liyanage
  • 4,706
  • 9
  • 36
  • 50

2 Answers2

4

Is this due to shallow copy and deep copy?

Yes. clone() only performs a shallow copy.

The clone method copies the content of the first dimension. In the first example, the array only have 1 dimension and consists of integers (which is a value type), so all the integers are copied. This is still a shallow copy. If you made the same example with reference types in the array, you would see the same behavior as with the multidimensional array.

In the 2nd example, you have a 2 dimensional array, which is basically an array of arrays, so the "first array" contains references. When you clone the multidimensional array, the references to the arrays are copied and not the content of those arrays (since it is not a deep copy).

MAV
  • 7,260
  • 4
  • 30
  • 47
  • Very nicely explained. Follow this image to understand more of what is explained above. https://www.geeksforgeeks.org/wp-content/uploads/Blank-Diagram-Page-1-12.jpeg – Jain Feb 21 '20 at 11:10
0

Change int[][] arrnew=arr.clone(); to int[][] arrnew=(int[][]) arr.clone();
And it will behave same as in the case of 1D array

pratim_b
  • 1,160
  • 10
  • 29