In Java, Collections.copy(dest, src) copies every element of src into dest, starting at index 0. Element i of the source overwrites element i of the destination. The method returns nothing.
It does not make a new list and does not grow the destination. The destination must already have at least as many elements as the source. Any extra elements at the end of the destination are left unchanged.
A static method of the java.util.Collections utility class, available since Java 1.2. Call it on the class name, as in Collections.copy(...), after import java.util.Collections;. You never create a Collections object.
Syntax
Pass the destination first and the source second.
Java
List<String> dest = new ArrayList<>(Arrays.asList("a", "b", "c", "d"));
List<String> src = Arrays.asList("X", "Y");
Collections.copy(dest, src); // dest = [X, Y, c, d]
Call
What it does
Collections.copy(dest, src)
Overwrites the first src.size() elements of dest.
Collections.copy(dest.subList(k, k + n), src)
Copies to an offset k.
new ArrayList<>(src)
The usual way to make a brand-new copy.
dest.addAll(src)
Appends instead of overwriting.
The copy is shallow: both lists end up holding references to the same element objects. The order of the arguments follows the pattern "destination, source", the same as System.arraycopy in spirit.
Library declarations
Java
// java.util.Collections
public static <T> void copy(List<? super T> dest, List<? extends T> src)
Parameters
Parameter
Description
dest
The list to copy into. Its size must be at least src.size(), and it must support set.
src
The list to copy from. It is not changed.
Return Value
Return Value
Description
void
Nothing. The first elements of dest now match src.
Compare with Similar Methods
Ways to copy elements between lists:
Method
How it differs
new ArrayList<>(src)
Creates a new list of the right size; no size rule to worry about.