w3resource

Java: Copy one array list into another


9. Copy ArrayList

Write a Java program to copy one array list into another.

Sample Solution:-

Java Code:

import java.util.*;
  public class Exercise9 {
  public static void main(String[] args) {
  List<String> List1 = new ArrayList<String>();
  List1.add("1");
  List1.add("2");
  List1.add("3");
  List1.add("4");
  System.out.println("List1: " + List1);
  List<String> List2 = new ArrayList<String>();
  List2.add("A");
  List2.add("B");
  List2.add("C");
  List2.add("D");
  System.out.println("List2: " + List2);
  // Copy List2 to List1
  Collections.copy(List1, List2);
  System.out.println("Copy List to List2,\nAfter copy:");
  System.out.println("List1: " + List1);
  System.out.println("List2: " + List2);
 }
}

Sample Output:

List1: [1, 2, 3, 4]                                                    
List2: [A, B, C, D]                                                    
Copy List to List2,                                                    
After copy:                                                            
List1: [A, B, C, D]                                                    
List2: [A, B, C, D]

Flowchart:

Flowchart: Copy one list into another.

For more Practice: Solve these Related Problems:

  • Write a Java program to copy an ArrayList into a new ArrayList using the clone() method and then modify the copy without affecting the original.
  • Write a Java program to copy one ArrayList into another using addAll() and then sort the new list.
  • Write a Java program to deep copy an ArrayList of custom objects ensuring changes to the copy do not affect the original.
  • Write a Java program to copy an ArrayList into a new list using Java streams and collect(), then display both lists.

Go to:


PREV : Sort ArrayList.
NEXT : Shuffle 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.