To deep copy a list in Java, you need to create a new list and copy each element from the original list to the new list. This ensures that changes made to the copied list do not affect the original list or its elements.
In this example,
originalList
containing lists as elements.deepCopiedList
.originalList
and deep copy it to deepCopiedList
.deepCopiedList
contains deep copies of all elements of originalList
.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<List<Integer>> originalList = new ArrayList<>();
originalList.add(new ArrayList<>(List.of(1, 2)));
originalList.add(new ArrayList<>(List.of(3, 4)));
List<List<Integer>> deepCopiedList = new ArrayList<>();
for (List<Integer> sublist : originalList) {
deepCopiedList.add(new ArrayList<>(sublist));
}
System.out.println("Original List: " + originalList);
System.out.println("Deep Copied List: " + deepCopiedList);
}
}
Original List: [[1, 2], [3, 4]] Deep Copied List: [[1, 2], [3, 4]]
In this tutorial, we learned How to deep Copy a List in Java language with well detailed examples.