Java Collections - copy() Method
The java.util.Collections.copy() method is used to copy all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected.
Syntax
public static <T> void copy(List<? super T> dest, List<? extends T> src)
Here, T is the type of element in the list.
Parameters
dest |
Specify the destination list. |
src |
Specify the source list. |
Return Value
void type.
Exception
- Throws IndexOutOfBoundsException, if the destination list is too small to contain the entire source List.
- Throws UnsupportedOperationException, if the destination list's list-iterator does not support the set operation.
Example:
In the example below, the java.util.Collections.copy() method is used to copy all of the elements of list1 into list2.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a list objects List<Integer> list1 = new ArrayList<Integer>(); List<Integer> list2 = new ArrayList<Integer>(); //populating list1 list1.add(10); list1.add(20); list1.add(30); //populating list2 list2.add(100); list2.add(200); list2.add(300); //copying all elements of list1 into list2 Collections.copy(list2, list1); //printing the list1 System.out.println("list1 contains: " + list1); //printing the list2 System.out.println("list2 contains: " + list2); } }
The output of the above code will be:
list1 contains: [10, 20, 30] list2 contains: [10, 20, 30]
❮ Java.util - Collections