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.
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.
Alternatively, you can use the java.util.ArrayList.copyOf
method to create a new ArrayList that is a copy of the original list, and the java.util.Arrays.copyOf
method to create a new array that is a copy of the original array.
Here is an example:
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
List<String> clone = new ArrayList<>(Arrays.asList(Arrays.copyOf(list.toArray(), list.size())));
This will create a new ArrayList object with new String
objects that are copies of the strings in the original list.