w3resource

Java Collection, ArrayList Exercises: Copy one array list into another

Java Collection, ArrayList Exercises: Exercise-9 with Solution

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.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?



Java: Tips of the Day

Choice between Float and Double:

Data type Bytes used Significant figures (decimal)
Float 4 7
Double 8 15

Double is often preferred over float in software where precision is important because of the following reasons:
Most processors take nearly the same amount of processing time to perform operations on Float and Double. Double offers far more precision in the same amount of computation time.

Ref: https://bit.ly/3oj7K2K