Open In App

How to Implement a Generic Deep Copy Method for Multidimensional Arrays in Java?

There are two types of copies in Java that can be made of any data structure. Deep copy and Shallow copy. In Shallow copy when we copy an array into another the new variable is created but it points to the same address space. This means if we make any changes in the newly copied array it will also get copied in the original array.

On the other hand, when we make a deep copy of an array the array is assigned a new memory space, and the content is copied in the new memory space. This means that if we make changes in any of the two arrays it will not get changed in the second array. In this article, we will see how to make a generic deep copy method for multidimensional arrays in Java.

Example:

Input: { {1,2}, {3,2}, {5,6} , {3,3} }
Output: { {1,2}, {3,2}, {5,6} , {3,3} }

We will implement the following method to make a generic deep copy of the multidimensional array.

Method to Implement Generic Deep Copy of Multidimensional Array

In this method, we will take the original array, and then by calculating its dimensions we will declare a new generic array and then copy the elements in the original array to the new array one by one. We will follow the steps given below to implement this.

  1. Calculate the dimensions of the given original Array.
  2. Declare a new generic array with the same dimensions as calculated in the previous step.
  3. Use a nested loop in which the outer loop will run till a number of rows and the inner loop will run till the number of columns.
  4. Save each element in the original array into a new array.
  5. Return the copy.

Code:

import java.lang.reflect.Array;
import java.util.Arrays;

public class Main {

    @SuppressWarnings("unchecked")
    public static <T> T[][] deepCopy(T[][] original) {
        if (original == null) {
            return null;
        }

        // Get the dimensions of the original array
        int rows = original.length;
        int cols = original[0].length;

        // Correctly instantiate a new array of the same type and dimensions
        T[][] copy = (T[][]) Array.newInstance(original.getClass().getComponentType(), rows, cols);

        // Nested loops to copy the elements
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                copy[i][j] = original[i][j];  // Shallow copy of elements
            }
        }

        return copy;
    }

    public static void main(String[] args) {
        Integer[][] original = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        Integer[][] copied = deepCopy(original);

        // Modify the original array
        original[0][0] = 100;

        // Verify that the copied array remains unchanged
        System.out.println("Original array: " + Arrays.deepToString(original));
        System.out.println("Copied array: " + Arrays.deepToString(copied));
    }
}

Output:

Original array: [[100, 2, 3], [4, 5, 6], [7, 8, 9]]
Copied array: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Time and Space complexity:

Time Complexity: O(M*N)
Space Complexity: O(M*N)

Article Tags :