Skip to content

Java ArrayList add array example

Java ArrayList add array example shows how to add all elements of an array to ArrayList in Java. The example also shows how to add array to ArrayList using various ways.

How to add Array to ArrayList in Java?

There are various ways to add an array to ArrayList in Java.

1)    Using the addAll method of Collections class

You can use addAll method of Collections class to add array to ArrayList.

This method adds all specified elements to the argument collection.

Example

Output

2)    Using the asList method of Arrays class and addAll method of ArrayList

You can use asList method of Arrays class to convert an array to the List object first.

This method returns a fixed size List object backed by the original argument array.

Once you get the List object, you can add the list object to the ArrayList using addAll method of ArrayList.

This method adds all elements of the specified collection at the end of the ArrayList object.

Example

Output

What is the preferred way to add array to ArrayList?

Using addAll method of Collections class (approach 1) is preferred over using asList method of Arrays and addAll method of ArrayList class (approach 2) because it is faster in terms of performance under most implementation.

This example is a part of the ArrayList in Java tutorial and Array in Java tutorial.

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

About the author

Leave a Reply

Your email address will not be published.