Write a Java program to copy one array list into another


This is a Java program that demonstrates how to copy elements from one ArrayList to another using the Collections.copy() method. Here's a brief explanation of the code:

  • The program defines a class called Copy_ArrayList.
  • In the main() method, two ArrayLists are created: arr_List1 and arr_List2.
  • Five elements are added to each of the ArrayLists using the add() method.
  • The println() method is used to print the elements of both ArrayLists.
  • The Collections.copy() method is called to copy the elements from arr_List1 to arr_List2.
  • The println() method is used again to print the elements of both ArrayLists, showing that the elements of arr_List2 have been replaced with the elements of arr_List1.

Note that the Collections.copy() method requires that the destination list (arr_List2 in this case) be at least as large as the source list (arr_List1 in this case). If the destination list is smaller than the source list, an IndexOutOfBoundsException will be thrown.

Source Code

import java.util.*;
public class Copy_ArrayList
{
	public static void main(String[] args)
	{
		List<String> arr_List1 = new ArrayList<String>();
		arr_List1.add("10");
		arr_List1.add("20");
		arr_List1.add("30");
		arr_List1.add("40");
		arr_List1.add("50");
		List<String> arr_List2 = new ArrayList<String>();
		arr_List2.add("A");
		arr_List2.add("B");
		arr_List2.add("C");
		arr_List2.add("D");
		arr_List2.add("E");
		System.out.println("List1 : " + arr_List1);
		System.out.println("List2 : " + arr_List2);
		Collections.copy(arr_List2, arr_List1);
		System.out.println("Copy List1 to List2");
		System.out.println("List1 : " + arr_List1);
		System.out.println("List2 : " + arr_List2);
	}
}

Output

List1 : [10, 20, 30, 40, 50]
List2 : [A, B, C, D, E]
Copy List1 to List2
List1 : [10, 20, 30, 40, 50]
List2 : [10, 20, 30, 40, 50]

Example Programs