Java Collections copy() Method
Example
Copy the items of one list into the start of another list:
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
ArrayList<String> newCars = new ArrayList<String>();
newCars.add("Mazda");
Collections.copy(cars, newCars);
System.out.println(cars);
}
}
Definition and Usage
The copy() method copies all items from one list (the source) into another list (the destination). Each item replaces the item at the same index in the destination list.
The destination list must have at least as many items as the source list. The other items in the destination list do not change.
Syntax
public static void copy(List<T> dest, List<T> src)
T refers to the data type of items in the list.
Parameter Values
| Parameter | Description |
|---|---|
| dest | Required. The list to copy the items into. |
| src | Required. The list to copy the items from. |
Technical Details
| Returns: | No return value. |
|---|---|
| Throws: | IndexOutOfBoundsException - if the destination list has fewer items than the source list. |
Related Pages
Java Collections Framework Tutorial
❮ Collections Methods