Collections copy() method in Java with Examples
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.
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
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
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
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.