w3resource

Java: Clone an array list to another array list


16. Clone ArrayList

Write a Java program to clone an array list to another array list.

Pictorial Presentation:

Java Collection, ArrayList Exercises: Clone an array list to another array list

Sample Solution:-

Java Code:

import java.util.ArrayList;
import java.util.Collections;
  public class Exercise16 {
  public static void main(String[] args) {
          ArrayList<String> c1= new ArrayList<String>();
          c1.add("Red");
          c1.add("Green");
          c1.add("Black");
          c1.add("White");
          c1.add("Pink");
          System.out.println("Original array list: " + c1);
          ArrayList<String> newc1 = (ArrayList<String>)c1.clone();
          System.out.println("Cloned array list: " + newc1);       
}
}

Sample Output:

Note: Exercise16.java uses unchecked or unsafe operations.              
Note: Recompile with -Xlint:unchecked for details.                     
Original array list: [Red, Green, Black, White, Pink]                  
Cloned array list: [Red, Green, Black, White, Pink]

Flowchart:

Flowchart: Clone an array list to another array list.

For more Practice: Solve these Related Problems:

  • Write a Java program to clone an ArrayList using the clone() method and then modify the clone without affecting the original.
  • Write a Java program to perform a deep clone of an ArrayList of custom objects using serialization.
  • Write a Java program to clone an ArrayList using the copy constructor and then sort the cloned list.
  • Write a Java program to use Java streams to create a copy of an ArrayList and validate that both lists are identical.

Go to:


PREV : Join Two ArrayLists.
NEXT : Clear ArrayList.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.