Mega Code Archive

 
Categories / Java Tutorial / Collections
 

Copying and Cloning Lists

When you call the clone() method of an ArrayList, a shallow copy of the list is created. The new list refers to the same set of elements as the original. It does not duplicate those elements. Since clone() is a method of the ArrayList class and not the List (or Collection) interface, you must call clone() on a reference to the class, not the interface. import java.util.ArrayList; import java.util.List; public class MainClass {   public static void main(String[] a) {     List list = new ArrayList();     list.add("A");     List list2 = ((List) ((ArrayList) list).clone());     System.out.println(list);     System.out.println(list2);     list.clear();     System.out.println(list);     System.out.println(list2);   } } [A] [A] [] [A]