Last Updated:

How do I convert an array to an ArrayList in Java?

Arrays.asList(T... a) is an easy and quick way to convert an array to an ArrayList in Java, but this method returns the original array as an ArrayList. The resulting ArrayList will be of a fixed size and any attempt to change anything in it will result in an UnsupportedOperationException at run time. In addition, any change to the array will also change the elements in the ArrayList!

Collections.addAll(ArrayList strList, T[] strArr) is the best way to convert an Array to an ArrayList because the data array is copied to the list as a stand-alone object. This means that the source array and the resulting ArrayList will be independent of each other.

Now let's see these methods in action:

ArrayToArrayList.java

The result of the program will be as follows:

Obtained ArrayList using Arrays.asList() method
1 2 3 4
Changes to the array affected the ArrayList as well
5 2 3 4
Array to ArrayList with Collections.addAll() method
5 2 3 4 5