VOOZH about

URL: https://www.geeksforgeeks.org/java/collections-copy-method-in-java-with-examples/

⇱ Collections copy() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Collections copy() method in Java with Examples

Last Updated : 15 May, 2019
The copy() method of java.util.Collections class 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. This method runs in linear time. Syntax:
public static void copy(List dest, List src)
Parameters: This method takes the following argument as a parameter
  • dest - The destination list.
  • src - The source list.
Exception: This method throws IndexOutOfBoundsException, if the destination list is too small to contain the entire source List. Below are the examples to illustrate the checkedSortedSet() method Example 1:
Output:
Value of source list: [Ram, Gopal, Verma]
Value of destination list: [1, 2, 3]

After copying:

Value of source list: [Ram, Gopal, Verma]
Value of destination list: [Ram, Gopal, Verma]
Example 2: For IndexOutOfBoundsException
Output:
Value of source list: [Ram, Gopal, Verma]
Value of destination list: [1, 2]

After copying:

Exception thrown : 
java.lang.IndexOutOfBoundsException:
 Source does not fit in dest
Comment