Java - Copy a List to Another List using Collections.copy() method

The Collections class consists exclusively of static methods that operate on or return collections.

Using Collections.copy() method

One of them is a copy() method, which needs a source list and a destination list at least as long as the source.
This method copies all elements of the source list to the destination list. After the copy index of the elements in both source and destination lists would be identical.
The destination list must be long enough to hold all copied elements. If it is longer than that, the rest of the destination list's elements would remain unaffected.
package net.javaguides.examples;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Different ways to copy a list into another list
 * 
 * @author Ramesh Fadatare
 *
 */
public class CopyListExamples {

    public static void main(String[] args) {

        List < String > fruits1 = new ArrayList < > ();
        // Adding new elements to the ArrayList
        fruits1.add("Banana");
        fruits1.add("Apple");
        fruits1.add("mango");
        fruits1.add("orange");
        System.out.println(fruits1);

        // using the Collections.copy() method
        List < String > fruits2 = new ArrayList < > (fruits1.size());
        fruits2.add("1");
        fruits2.add("2");
        fruits2.add("3");
        fruits2.add("4");
        Collections.copy(fruits2, fruits1);

        System.out.println(fruits2);
    }
}
Output:
[Banana, Apple, mango, orange]
[Banana, Apple, mango, orange]
Checkout Copy a List to Another List in Java (5 Ways) - 5 different ways to copy a List to another List with an example.
  1. Using Constructor
  2. Using addAll() method
  3. Using Collections.copy() method
  4. Using Java 8
  5. Using Java 10

References

https://www.javaguides.net/2020/02/copy-list-to-another-list-in-java-5-ways.html

Comments