How to Make a Deep Copy of Java ArrayList?
Last Updated :
08 Feb, 2024
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
import java.util.ArrayList;
public class DeepCopyExample {
private static ArrayList<String>
deepCopy(ArrayList<String> originalList)
{
ArrayList<String> copiedList = new ArrayList<>();
for (String item : originalList) {
copiedList.add( new String(item));
}
return copiedList;
}
public static void main(String[] args)
{
ArrayList<String> originalList = new ArrayList<>();
originalList.add( "1" );
originalList.add( "2" );
originalList.add( "3" );
ArrayList<String> copiedList
= deepCopy(originalList);
copiedList.add( "4" );
System.out.println( "Original List: "
+ originalList);
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 an ArrayList
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.
Share your thoughts in the comments
Please Login to comment...