Java ArrayList copy

There are several ways to create a copy of an ArrayList in Java:

  1. You can use the clone() method of the ArrayList class to create a shallow copy of the ArrayList. A shallow copy means that the copy and the original ArrayList share the same elements, but they are stored in different objects. Here is an example:
ArrayList<String> original = new ArrayList<>();
original.add("item1");
original.add("item2");

ArrayList<String> copy = (ArrayList<String>) original.clone();
  1. You can use the ArrayList constructor to create a new ArrayList and copy the elements of the original ArrayList to the new ArrayList using the addAll() method:
ArrayList<String> original = new ArrayList<>();
original.add("item1");
original.add("item2");

ArrayList<String> copy = new ArrayList<>(original);
  1. You can use the copyOf() method of the java.util.Arrays class to create a copy of the ArrayList. This method creates a new ArrayList and copies the elements of the original ArrayList to the new ArrayList. Here is an example:
ArrayList<String> original = new ArrayList