Programming Tips - Java: Quick way to make a copy of an ArrayList

Date: 2016jun8 Update: 2025oct21 Language: Java Keywords: duplicate, clone Q. Java: Quick way to make a copy of an ArrayList A. Usually I prefer to copy it in the constructor:
ArrayList<String> theClone = new ArrayList<String>(theOriginal);
Here's a full demo showing two ways to do it:
import java.util.ArrayList; class Demo { public static void main(String[] args) { // Make "original" ArrayList ArrayList<String> theOriginal = new ArrayList<String>(); theOriginal.add("one"); theOriginal.add("two"); theOriginal.add("three"); { // You can make a copy in the constructor ArrayList<String> theCopy1 = new ArrayList<String>(theOriginal); System.out.println("theCopy1=" + theCopy1); } // Or you can copy using `addAll()` { ArrayList<String> theCopy2 = new ArrayList<String>(); theCopy2.addAll(theOriginal); System.out.println("theCopy2=" + theCopy2); } } }
Output:
theCopy1=[one, two, three] theCopy2=[one, two, three]