Collections

Java Array to ArrayList Example

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

How to convert array to ArrayList in Java?

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

1) Using 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 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 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, addAll method will append the elements of array to the ArrayList.

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

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