Skip to content

Java ArrayList copy elements example

Java ArrayList copy elements example shows how to copy ArrayList elements to another ArrayList. The 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 the copy method of Collections class

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

This method copies all elements from the source list to the destination list. Index of the destination list elements will be the same after the copy operation.

Output

As you can see from the output, elements of the aListWeekend are copied to the aListDays at the identical index such that the first element of the source list becomes the 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 the source list contains 2 elements and destination contains 5, after the copy, the 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 the source list, copy method throws IndexOutOfBoundException. Consider below given example.

Output

2) Copy ArrayList using the addAll method

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

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

Output

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

3) Copy ArrayList using ArrayList constructor

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

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

Output

This example is a part of the Java ArrayList tutorial with examples.

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

About the author

Leave a Reply

Your email address will not be published.