Skip to content

Java Array to ArrayList Example

Java Array to ArrayList example shows how to convert array to ArrayList in Java. The example also shows how to convert array to ArrayList using various ways.

Java ArrayList is a part of the Java Collection framework.

How to convert array to ArrayList in Java?

There are several ways using which we can convert array to ArrayList in Java.

1) Using the asList method of Arrays class

We can use asList method of Arrays class to convert array to ArrayList. The asList method returns a fixed sized list backed by the original array. Think of it as a list wrapper around the array.

Output

As you can see from the output, any elements you change in the list is also reflected back to the array. One important thing to note is you cannot change the list structurally i.e. add or remove elements from the list obtained in this way.

If you want ArrayList instead of List object, you can use the ArrayList constructor which accepts List argument as given below.

Output

Since we have created a new ArrayList object using constructor, you can change the ArrayList as you wish and the changes will not be reflected back to the original array.

2) Using the addAll method of Collections class

We can use addAll method of Collections class to add all the elements of the array to empty ArrayList as given below.

Output

3) Using Apache Commons

If you are using Apache Commons library, you can use addAll method of CollectionUtils class to add all elements of the array to ArrayList as given below.

Output

For options 2 and 3, make sure that the ArrayList is empty before adding all the elements of the array. If ArrayList is not empty, the addAll method will append the elements of array to the ArrayList.

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

References:
1) ArrayList Javadoc
2) Apache Commons CollectionUtils class

About the author

Leave a Reply

Your email address will not be published.