W3docs

Java ArrayList copy

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

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 element references, but they are stored in different objects. Both clone() and the constructor perform shallow copies. 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 it:

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 List interface to create a copy of the ArrayList. This method creates a new list and copies the elements of the original ArrayList to the new list. Note that the returned list is unmodifiable. Here is an example:

ArrayList<String> original = new ArrayList<>();
original.add("item1");
original.add("item2");

List<String> copy = List.copyOf(original);