Collections

Java ArrayList copy elements example

Java ArrayList copy elements example shows how to copy ArrayList elements to another ArrayList. Example also shows how to copy all elements of ArrayList to another ArrayList using various approaches.

How to copy ArrayList elements to another ArrayList in Java?

There are several ways to copy ArrayList elements to another ArrayList as given below.

1) Copy ArrayList using copy method of Collections class

You can copy elements of one ArrayList to another using copy method of Collections class.

This method copies all elements from sourceList to destinationList. Index of destinationList elements will be same after copy operation.

Output

As you can see from the output, elements of aListWeekend are copied to aListDays at the identical index such that first element of source list becomes first element of destination list and so on.

Note 1: If the destination list is larger than the source list, all remaining elements of the destination list will be kept as is. i.e. if source list contains 2 elements and destination contains 5, after copy destination list will still retain its last 3 elements. Consider below given example.

Output

As you can see from the output, “Four” is copied at first index in the destination list but it still retained “Two” and “Three” elements.

Note 2: If the destination list is not large enough to contain all the elements of source list, copy method throws IndexOutOfBoundException. Consider below given example.

Output

2) Copy ArrayList using addAll method

You can use addAll method to copy elements of ArrayList to another ArrayList.

addAll method appends all elements of the specified collection to the end of the ArrayList.

Output

Kindly note that addAll method appends the elements of one List to another. So, if destination List already has elements, source list’s elements will be copied after them.

3) Copy ArrayList using ArrayList constructor

You can use ArrayList constructor to copy elements from another List.

This constructor creates new ArrayList containing the elements of the specified collection (in order they are returned from collection’s Iterator).

Output

Please let us know your views in the comments section below.

 

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.