Last Updated:

TOP-3 ways to convert an array to An ArrayList. Example in Java

In this article, we'll look at the most popular ways to convert Java arrays into the ArrayList collection.

First of all, let's look at the array with which we will work:

An array of some objects for 3 elements.

Third place. Use the Collections.addAll() method

Let's look at an example:

First, we created an empty listOfObjects of the same length as the array with the original data. Then, using the method, we added all the elements of the arrayOfObjects to the listOfObjects collection.Collections.addAll()

Second place. Use the Arrays.asList() method

In this popular way of converting an array to a list, the method will be used:

Arrays.asList()

Yes, this is a concise and convenient way, but clearly not the best. The thing is that the length of the list that we will get by the method is fixed. In fact, this list is not , but an internal static class defined inside . We know that this is implemented as an array, so the method will return a fixed-size list based on the original array. Thus, if we try to add or remove items from such a list, we get . Read more about it here.

asList()java.util.ArrayListjava.util.ArraysArrayListasList()UnsupportedOperationException

TOP-1. Convert the array to ArrayList

The most popular method is as follows:

At first glance, this method is not much different from the first two, but let's look at it in more detail:

We used the constructor , which, according to JavaDoc, creates a list containing the items of the specified collection in the order in which they were returned by the collection iterator. In other words, the collection is first converted to an array and then stored in an internal array. Under the hood, it looks like this:ArrayList(Collection < ? extends E > c)elementData

As you can see, each of the methods performs the task assigned to it to create an ArrayList collection from an array, but you need to choose them wisely.