Skip to content

Java convert String array to ArrayList example

This example shows how to convert String array to ArrayList in Java using Arrays, Collections, and Apache Commons including what is the most efficient way to convert.

How to convert String array to ArrayList in Java?

1) Convert Java String array to List using the Arrays class

Use the asList method of the Arrays class to convert string array to a List object.

Example

Output

Please note that the List object returned by the asList method is a fixed sized list which is backed by the original array. Adding or removing any elements from the list will throw java.lang.UnsupportedOperationException exception. However, you can update the values in the list.

Output

Output

2) Using the Collections class

Use the addAll method of the Collections class to add all elements of an array to the ArrayList.

Output

Please note that, if the ArrayList object had some elements before the Collections.addAll method is called, all the elements of the String array will be added after existing elements of the ArrayList object.

3) Using Apache Commons Collections

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

What is the best way to convert String array to ArrayList?

If you do not intend to add or remove elements from the ArrayList after converting it from the string array, use the List object returned directly from the asList method of the Arrays class. This is an efficient approach to convert string array to an ArrayList because it does not create a copy of an original array and operate on the same array.

If you want to add or remove elements from the ArrayList, convert that list to an ArrayList using the ArrayList constructor as given in the example code, or use the addAll  method of the Collections or CollectionUtils class.

This example is a part of the Java String tutorial and ArrayList 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.