This post shows you how to copy a List to another List with an example.
https://www.javaguides.net/2020/02/copy-list-to-another-list-in-java-5-ways.html
Copy a List to Another List Example
A simple way to copy a List is by using the constructor that takes a collection as its argument:
package net.javaguides.examples;
import java.util.ArrayList;
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 > fruits = new ArrayList < > ();
// Adding new elements to the ArrayList
fruits.add("Banana");
fruits.add("Apple");
fruits.add("mango");
fruits.add("orange");
System.out.println(fruits);
// using constructor
List < String > copyFruits = new ArrayList < > (fruits);
System.out.println(copyFruits);
}
}
Output:
[Banana, Apple, mango, orange]
[Banana, Apple, mango, orange]
This approach isn't thread-safe. We may get ConcurrentAccessException error, to fix this problem we may need to use CopyOnWhiteArrayList, in which all mutative operations are implemented by making a fresh copy of the underlying array.
Checkout Copy a List to Another List in Java (5 Ways) - 5 different ways to copy a List to another List with an example.
- Using Constructor
- Using addAll() method
- Using Collections.copy() method
- Using Java 8
- Using Java 10
Comments
Post a comment