Search code examples
javaarraysdeep-copyshallow-copy

Array deep copy and shallow copy


I'm learning deep copy and shallow copy.

If we have two arrays:

int[]arr1={1,2,3,4,5};
int[]arr2={1,2,3,4,5};

Question: Both arrays point to the same references [1][2][3][4][5].

What will happen if I change arr1[2]?Does it changes arr2[2]?

When we pass an array (random array, not necessarily arr1 or arr2) from main into a method the compiler makes a shallow copy of the array to the method, right?

If the Java compiler was re-written to make and send a deep copy of the array data to the method. What happens to the original array in the main? I think the original array may change according to the method and pass back into the main. I am not sure.


Solution

  • Question: Both arrays point to the same references [1][2][3][4][5].

    Not exactly. Your arrays have identical content. That being said, as per your initialization, they data they are using is not shared. Initializing it like so would however:

    int[]arr1={1,2,3,4,5};
    int[] arr2 = arr1
    

    What will happen if I change arr1[2]?Does it changes arr2[2]?

    As per the answer to the above question, no it will not. However, if you were to change your initialization mechanism as per the one I pointed out, it would.

    When we pass an array (random array, not necessarily arr1 or arr2) from main into a method the compiler makes a shallow copy of the array to the method, right?

    Your method will receive a location where to find the array, no copying will be done.

    If the Java compiler was re-written to make and send a deep copy of the array data to the method. What happens to the original array in the main? I think the original array may change according to the method and pass back into the main. I am not sure.

    If you were to create a deep copy of the array and send it to your method, and your method will work on that copy, then, the original array should stay the same.