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.

Syntax

Following is the declaration of copy() method:

Parameter

ParameterDescriptionRequired/Optional
destIt is a destination list in which elements are to be copied.Required
srcIt is the source list to be copied its elements into destination.Required

Returns

The copy() method does not return anything.

Exceptions

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.

Compatibility Version

Java 1.4 and above

Example 1

Test it Now

Output:

Elements of source list: [Java Tutorial, is best on, JavaTpoint]
Elements of destination list: [Java Tutorial, is best on, JavaTpoint]

Example 2

Test it Now

Output:

1 2 3 4 9 10 

Example 3

Test it Now

Output:

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 4

Test it Now

Output:

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]





Latest Courses