Collections

Java ArrayList add array example

Java ArrayList add array example shows how to add all elements of an array to ArrayList in Java. 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 array to ArrayList in Java.

1)    Using 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 asList method of Arrays class and addAll method of ArrayList

You can use asList method of Arrays class to convert an array to 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 the list object to the ArrayList using addAll method of ArrayList.

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

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.

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

Join 1000+ fellow learners! Enter your email address below: