Collections Java String Handling

Java convert String array to ArrayList example

This example shows how to convert String array to ArrayList in Java. This example also shows several ways to convert String array to ArrayList in Java and what is the most efficient way.

How to convert String array to ArrayList in Java?

There are several ways in which you can convert Java String array to ArrayList of String as given below.

1) Convert Java String array to List using Arrays class

Use asList() method of Arrays class to convert String array to List object.

Example

Output

Please note that the List object returned by 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. However, you can update the values in the list.

Output

Output

2) Convert Java String array to ArrayList using Collections class

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

Output

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

3) Convert String array to ArrayList using Apache Commons Collections

You can also use addAll method of 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 List object returned directly from the asList method of the Arrays class. This is efficient approach to convert String array to 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 the ArrayList using ArrayList constructor as given in the example code, or use Collections.addAll or CollectionUtils.addAll approach.

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

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

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *