Convert Java array to List and vice versa

One of the most common conversions done in Java programming language is the conversion of a primitive array to a Collection instance like a List for example. In this tutorial we’ll take a look at how to do it and talk about the possible issues which you might face.

Array to List

The usual tool to convert an array to List is the Arrays.asList method. It works fairly well but in some cases it may lead to unexpected results. Consider the following example:

int[] array = new int[] { 1, 2, 3, 4, 5 };
List list = Arrays.asList(array);

You might expect the list variable to contain the number from 1 to 5 but in fact it contains one int[] element. The reason is that in Java5 asList method got overloaded with varargs version which messes up things a bit.

To convert a primitive array to a List you need to loop the array and add the values on by one. You can do it for example like this:

List<Integer> list = new ArrayList<Integer>();
for (int i : array) {

With reference types it’s a little bit different story. If you write the same example like this:

Integer[] array = new Integer[] { 1, 2, 3, 4, 5 };

You get the result you expected. So the conversion works properly with reference type arrays, but not with primitive ones.

But there’s one catch. The List returned by Arrays.asList is fixed sized List. So you cannot add more values to it. If you need a dynamic list you have to create a new List instance like this:

Integer[] array = new Integer[] { 1, 2, 3, 4, 5 };
List<Integer> list = new ArrayList<Integer>(Arrays.<Integer>asList(array));

List to Array

A little bit less common case is the conversion from a List to an array. With reference types you can use the List.toArray method likes this:

Integer[] array = list.toArray(new Integer[list.size()]);

With primitive types it’s a little bit trickier. You need to loop the list and put the values to their right places:

int[] array = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
    array[i] = list.get(i);            

TIP If you need dynamic sized List always create new List instance instead of using the one Arrays.asList method returns directly


So the summarize the whole thing, when converting an array to a List and the array contains primitive types you need to loop the array. If the array contains reference types, then you can use Arrays.asList

And when converting a List to an array, with reference types you can use List.toArray method and with primitive type you need to loop.

Also don’t forget that Arrays.asList returns a fixed size List!

Further reading


comments powered by Disqus