Java Collections copy() MethodThe 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. SyntaxFollowing is the declaration of copy() method: Parameter
ReturnsThe copy() method does not return anything. ExceptionsThe 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 VersionJava 1.4 and above Example 1Test it NowOutput: Elements of source list: [Java Tutorial, is best on, JavaTpoint] Elements of destination list: [Java Tutorial, is best on, JavaTpoint] Example 2Test it NowOutput: 1 2 3 4 9 10 Example 3Test it NowOutput: 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 NowOutput: 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] Next TopicJava Collections Class |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India