Java Collections copy() Method
The copy() method of Java Collections class copies all of the elements from one list into another list. In this method, the size of the destination list must be greater than or equal to the size of the source list.
Following is the declaration of copy() method:
The copy() method does not return anything.
The copy() method throws the following exceptions-
IndexOutOfBoundsException- It throws an exception if the destination list is too small to store the entire source List.
UnsupportedOperationException- It throws this type of exception if the destination list's list-iterator does not support the set operation.
Java 1.4 and above
Example 1Test it Now
Elements of source list: [Java Tutorial, is best on, JavaTpoint] Elements of destination list: [Java Tutorial, is best on, JavaTpoint]
Example 2Test it Now
1 2 3 4 9 10
Example 3Test it Now
Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest at java.base/java.util.Collections.copy(Collections.java:558) at myPackage.CollectionsCopyExample3.main(CollectionsCopyExample3.java:8)
Example 4Test it Now
Elements of Source List: [50, 10, 20] Elements of Destination List: [one, two, three, four, five] Elements of Destination List after copying Source List: [50, 10, 20, four, five]