Sobes.tech
Junior — Middle

Explain the process of copying a two-dimensional array and how to create its independent copy.

sobes.tech AI

Answer from AI

In Java, a two-dimensional array is an array of arrays, meaning each element of the outer array is a reference to an inner array. A simple assignment of a two-dimensional array creates a shallow copy, where only the references to the inner arrays are copied, not the actual data.

To create a standalone (deep) copy of a two-dimensional array, you need to copy each inner array separately. For example:

int[][] original = {{1, 2}, {3, 4}};
int[][] copy = new int[original.length][];
for (int i = 0; i < original.length; i++) {
    copy[i] = new int[original[i].length];
    System.arraycopy(original[i], 0, copy[i], 0, original[i].length);
}

This way, we create a new outer array and allocate new memory for each inner array, copying the data. As a result, changes in the copy will not affect the original.