Copy Elements of One ArrayList to Another ArrayList with Java Collections Class


In order to copy elements of ArrayList to another ArrayList, we use the Collections.copy() method. It is used to copy all elements of a collection into another.

Declaration −The java.util.Collections.copy() method is declared as follows −

public static <T> void copy(List<? super T> dest,Lis<? extends T> src)

where src is the source list object and dest is the destination list object.

Let us see a program to copy elements of one ArrayList to Another ArrayList with Java Collections Class −

Example

 Live Demo

import java.util.*;
public class Example {
   public static void main (String[] args) {
      List<String> zoo = new ArrayList<String>();
      zoo.add("Zebra");
      zoo.add("Lion");
      zoo.add("Tiger");
      List<String> list = new ArrayList<String>();
      list.add("Hello");
      list.add("Hi");
      list.add("World");
      Collections.copy(list,zoo); // copying the ArrayList zoo to the ArrayList list
      System.out.println(list);
   }
}

Output

Zebra, Lion, Tiger]

Updated on: 25-Jun-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements