Home »
Java programming language
Java Collections copy() Method with Example
Collections Class copy() method: Here, we are going to learn about the copy() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on February 03, 2020
Collections Class copy() method
- copy() method is available in java.util package.
- copy() method is used to copy all the elements from List the src_list (source list) and place all the copied elements into List dst_list (destination list).
- copy() method is a static method, so it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
-
copy() method may throw an exception at the time of copying elements from one list to another.
- IndexOutOfBoundsException: This exception may throw when the given parameter dst_list size is lesser than the src_list.
- UnsupportedOperationException: This exception may throw when the given parameter dst_list un-support set operation.
Syntax:
public static void copy(List dst_list, List src_list);
Parameter(s):
- List dst_list – represents the destination list.
- List src_list – represents the source list.
Return value:
The return type of this method is void, it returns nothing.
Example:
// Java program is to demonstrate the example of
// void copy() method of Collections
import java.util.*;
public class Copy {
public static void main(String args[]) {
// Instantiate two LinkedList object
List < Integer > src_l = new LinkedList < Integer > ();
List < Integer > dest_l = new LinkedList < Integer > ();
// By using add() method is to add
// few elements in src_l
src_l.add(10);
src_l.add(20);
src_l.add(30);
src_l.add(40);
// By using add() method is to add
// few elements in dest_l
dest_l.add(60);
dest_l.add(70);
dest_l.add(80);
dest_l.add(90);
// Display LinkedList
System.out.println("src_l: " + src_l);
System.out.println("dest_l: " + dest_l);
// By using copy() method is to
// copy the elements of src_l into a dest_l
Collections.copy(dest_l, src_l);
System.out.println();
// Display Copied LinkedList
System.out.println("Collections.copy(dest_l, src_l): " + dest_l);
}
}
Output
src_l: [10, 20, 30, 40]
dest_l: [60, 70, 80, 90]
Collections.copy(dest_l, src_l): [10, 20, 30, 40]