How to Clone a List in Java?


To clone a list in Java, the easiest way is using the ArrayList.clone() method −

Example

import java.util.ArrayList;
public class Demo {
   public static void main(String args[]) {
      // create an empty array list
      ArrayList<StringBuilder> arrlist1 = new ArrayList<StringBuilder>();
      // use add for new value
      arrlist1.add(new StringBuilder("Learning-"));
      // using clone to affect the objects pointed to by the references.
      ArrayList arrlist2 = (ArrayList) arrlist1.clone();
      // appending the string
      StringBuilder strbuilder = arrlist1.get(0);
      strbuilder.append("list1, list2-both pointing to the same StringBuilder");
      System.out.println("The 1st list prints: ");
      // both lists will print the same value, printing list1
      for (int i = 0; i < arrlist1.size(); i++) {
         System.out.print(arrlist1.get(i) + " ");
      }
      System.out.println("
The 2nd list prints the same i.e:");       // both lists will print the same value, printing list2       for (int i = 0; i < arrlist2.size(); i++) {          System.out.print(arrlist2.get(i));       }    } }

Output

The 1st list prints:
Learning-list1, list2-both pointing to the same StringBuilder
The 2nd list prints the same i.e:
Learning-list1, list2-both pointing to the same StringBuilder

Example

Let us see another example to clone a List in Java −

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Example {
   public static void main(String[] args) {
      List<String> myList = Arrays.asList("Welcome", "to", "the", "website");
      System.out.print("Initial List = "+myList);
      List<String> newList = myList.stream().collect(Collectors.toList());
   }
}

Output

Initial List = [Welcome, to, the, website]
Cloned List = [Welcome, to, the, website]

Updated on: 24-Sep-2019

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements