clone arraylist java code example

Example 1: ArrayList clone() method in java

import java.util.ArrayList;
public class ArrayListCloneMethodExample
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("violet");
      al.add("indigo");
      al.add("blue");
      al.add("green");
      al.add("yellow");
      System.out.println("ArrayList before using clone() method: " + al);
      // create another ArrayList and copy
      ArrayList<String> arrClone = new ArrayList<String>();
      arrClone = (ArrayList)al.clone();
      System.out.println("ArrayList after using clone() method: " + arrClone);
   }
}

Example 2: copy arraylist java

List<Something> original=new ArrayList<>();
//insert elements
List<Something> copy=new ArrayList<>(original);//create copy here
System.out.println(copy.equals(original));//true because the copy has the same elements
System.out.println(copy==original);//false because it is another List

Tags:

Java Example