How to Make a Deep Copy of Java ArrayList?
The Advantage of ArrayList is it can be defined without giving a predefined size. But the disadvantage is it is more expensive to create and maintain. To have the solution for these expenses we can create a deep copy of an ArrayList.
There are two types of copies that can be made the first one is a deep copy and the second one is a shallow copy. In this article, we will learn to make a deep copy of Java ArrayList in Java.
Prerequisite
Deep Copy of ArrayList
Unlike shallow copy in deep copy, we entirely make a new ArrayList without referring to the old ArrayList. In this, instead of duplicating the ArrayList it also copies the objects in it. When we make a deep copy we entirely make a new ArrayList at the new address and then copy the elements one by one. Therefore if we make any changes in one list it doesn’t get reflected in the second ArrayList.
Following is the example of code in which we will make a deep copy of an ArrayList in Java.
Java
// Java Program to demonstrate Deep Copy of an ArrayList import java.util.ArrayList; public class DeepCopyExample { // Method to create a deep copy of an ArrayList private static ArrayList<String> deepCopy(ArrayList<String> originalList) { // Create a new ArrayList to store the copied // elements ArrayList<String> copiedList = new ArrayList<>(); // Iterate over each element in the original list for (String item : originalList) { // Creating a new instance of each element copiedList.add( new String(item)); } // Return the deep copied list return copiedList; } public static void main(String[] args) { // Creating the original ArrayList ArrayList<String> originalList = new ArrayList<>(); // Add string "1" to the list originalList.add( "1" ); // Add string "2" to the list originalList.add( "2" ); // Add string "3" to the list originalList.add( "3" ); // Creating a deep copy of the ArrayList ArrayList<String> copiedList = deepCopy(originalList); // Modify the copied list // Add string "4" to the copied list copiedList.add( "4" ); // Print both the original and copied lists // Print original list System.out.println( "Original List: " + originalList); // Print copied list System.out.println( "Copied List: " + copiedList); } } |
Output:
Original List: [1,2,3]
Copied List: [1,2,3,4]
Explaination of the above Program:
- A class method D
eepCopy
replicates each element of anArrayList
into a new instance, creating a truly independent copy. - Starting with “1”, “2”, and “3”, the program generates a deep copy of the list.
- Element “4” is added only to the copy, leaving the original unchanged.
- Both lists are displayed, revealing the separation.