The Wayback Machine - https://web.archive.org/web/20250115173201/https://www.geeksforgeeks.org/deep-copy-of-2d-array-in-java/
Open In App

Deep Copy of 2D Array in Java

Last Updated : 02 Feb, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Java, performing a deep copy of a 2D array containing objects requires careful consideration to ensure independence between the original and copied arrays. By creating new instances of objects for each element in the array, developers can achieve a true deep copy, preventing unintended side effects due to shared references.

In this article, we will learn to create a deep copy of a 2D array in Java.

Illustration of Shallow Copy Vs Deep Copy

Consider a 2D array 'originalArray' containing objects

Original Array : [[obj1, obj2] , [obj3], [obj4]]

Copy Type

Description

Example

Shallow Copy

Both arrays share references to the same objects

Shallow Copied Array : [[obj1, obj2] , [obj3], [obj4]]

Deep Copy

New instances of objects are created.

Deep copied array : [[newObj1, newObj2] , [newObj3], [newObj4]]

Java Program to Create Deep Copy of a 2D Array

Below is the implementation of the topic:

Java
// Java Program for Deep Copy of 2D Array
public class DeepCopy2DArray {
    // A simple class for illustration purposes
    static class MyClass {
        int value;

        MyClass(int value) {
            this.value = value;
        }
    }

    public static void main(String[] args) {
        // Create the original 2D array with objects
        MyClass[][] originalArray = {
            {new MyClass(1), new MyClass(2)},
            {new MyClass(3), new MyClass(4)}
        };

        // Perform the deep copy
        MyClass[][] deepCopiedArray = deepCopy2DArray(originalArray);

        // Modify an element in the original array to demonstrate independence
        originalArray[0][0].value = 99;

        // Display the original and deep copied arrays
        System.out.println("Original Array:");
        print2DArray(originalArray);

        System.out.println("\nDeep Copied Array:");
        print2DArray(deepCopiedArray);
    }

    // Method to perform a deep copy of a 2D array with objects
    private static MyClass[][] deepCopy2DArray(MyClass[][] originalArray) {
        int rows = originalArray.length;
        int cols = originalArray[0].length;

        MyClass[][] copiedArray = new MyClass[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                // Create a new instance of the object for each element
                copiedArray[i][j] = new MyClass(originalArray[i][j].value);
            }
        }

        return copiedArray;
    }

    // Method to print a 2D array with objects
    private static void print2DArray(MyClass[][] array) {
        for (MyClass[] row : array) {
            for (MyClass element : row) {
                System.out.print(element.value + " ");
            }
            System.out.println();
        }
    }
}

Output
Original Array:
99 2 
3 4 

Deep Copied Array:
1 2 
3 4 



Explanation of the above Program:

  • Create the Original 2D Array : We create a 2D array originalArray containing objects of the MyClass class.
  • Perform the Deep Copy : The deepCopy2DArray method is implemented to create a new array and instantiate new objects for each element, ensuring a deep copy.
  • Modify an Element in the Original Array : To demonstrate the independence of the deep copied array, we modify an element in the original array after the deep copy operation.
  • Display the Arrays : We print both the original and deep copied arrays to observe the effect of the modification.

Start your Java programming journey today with our Java Programming Online Course, designed for both beginners and advanced learners. With self-paced lessons covering everything from basic syntax to advanced concepts, you’ll gain the skills needed to excel in the world of programming.

Take the Three 90 Challenge! Complete 90% of the course in 90 days, and earn a 90% refund. Track your progress and stay motivated as you master Java.
Join now and start your path to becoming a Java expert!


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg