Primitive Arrays as a List

Noticed many times that conversion of int[] to List<Integer> is headache. When you write Arrays.asList(new int[]{1,2,3}); it will return List<int[]> and not List<Integer> ! I have done this mistake several times.

I was always trying something like this,

int[] ints = new int[]{1,2,3,4};
List<Integer> intList = Arrays.asList(ints);//arrrg!!!

Compiler started shouting at me that he is not able to convert List<int[]> to List<Integer>.

So, why can’t we call Arrays#asList like that ? Internally this method is doing something strange which returns List<int[]> and not List<Integer>.

When I started looking into the method, I found that method is directly passing these array in constructor of ArrayList. No! not java.util.ArrayList but java.util.Arrays.ArrayList. So this static inner class of Arrays is generic and has constructor which takes array as an argument.

Basically, this method is considering our int[] as a single Object of which list should be created. Worth to note that arrays in java are actually Objects. So, Arrays.asList(ints); call says create list of int[] and not Integer.

Quick alternative is that better to use Integer instead of int with array. Because Integer[] can be used with Array#asList to get List<Integer>. Yes! because in case of Integer[] method will consider them as Object[] and not single Object.

What if I can’t use Integer in place of int ? Well, in that case you have an option to iterate over array and add int elements directly to List. Because you can’t directly convert int[] to Integer[], for that you have to iterate over int[].

Same thing applies for other primitive types i.e long, double, float etc.

2 thoughts on “Primitive Arrays as a List

    1. Thanks for your comment. Yes it’s good to go with third party library if you can. Moreover, worth to note that Java8 is able to do this conversion in one line.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s