In this example, let us see how to copy all elements of one ArrayList object to another in Java.
Source Code
package com.beginner.examples;
import java.util.ArrayList;
import java.util.Collections;
public class CopyElementsToArrayList {
public static void main(String[] args) {
ArrayList al = new ArrayList();
// Add elements
al.add("A");
al.add("B");
al.add("C");
ArrayList al_copy = new ArrayList();
// Add elements
al_copy.add("a");
al_copy.add("b");
al_copy.add("c");
al_copy.add("d");
System.out.println("Copy the former:"+al_copy);
//It overlays the original element
Collections.copy(al_copy, al);
System.out.println("Copy after:" + al_copy);
}
}
Output:
Copy the former:[a, b, c, d]
Copy after:[A, B, C, d]
References
Imported packages in Java documentation: