How to clone ArrayList and also clone its contents?
To clone an ArrayList and also clone its contents, you can use the clone method of the ArrayList class, which creates a shallow copy of the list.
To clone an ArrayList and also clone its contents, you can use the clone method of the ArrayList class, which creates a shallow copy of the list.
Here is an example of how to clone an ArrayList of strings:
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
List<String> clone = (List<String>) list.clone();This will create a new ArrayList object that is a copy of the original list, but the strings in the list will not be cloned.
To also clone the contents of the list, you can use a loop to manually clone each element and add it to the new list. Here is an example:
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
List<String> clone = new ArrayList<>();
for (String s : list) {
clone.add(new String(s));
}This will create a new ArrayList object with new String objects that are copies of the strings in the original list. Note that this approach is specific to String; for other types, you would need to use a custom clone method, a copy constructor, or serialization.
Alternatively, you can use the ArrayList constructor or List.copyOf method (Java 10+) to create a new list that is a copy of the original. Like clone(), this performs a shallow copy, meaning the new list contains references to the same elements rather than independent copies.
Here is an example:
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
List<String> clone = new ArrayList<>(list);This will create a new list that references the same String objects as the original list. For a true deep copy, you must still iterate through the elements and create independent copies of each.