Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays.asList return type mismatch confusion [duplicate]

Why does the following not return a list of integers?

int[] ints = new int[] { 1, 2, 3, 4, 5 };
List<Integer> intsList = Arrays.asList(ints); //compilation error

But instead a List of int[]

While this

String[] strings = new String[] { "Hello", "World" };
List<String> stringsList = Arrays.asList(strings);

Returns a list of String. I am guessing it fails due to it being an array of primitives but why? And how do I actually return a list of int.

like image 471
arynaq Avatar asked Dec 15 '22 10:12

arynaq


2 Answers

It's because Arrays.asList(new int[] { 1, 2, 3, 4, 5 }) will create a List<int[]> with one item, not a List<Integer> with five items.

Note however that this would do what you expected:

List<Integer> intsList = Arrays.asList(1, 2, 3, 4, 5);

Your other alternatives are:

  • to create an Integer[] in the first place, or
  • to populate your list in a loop
like image 64
assylias Avatar answered Jan 08 '23 07:01

assylias


The method is defined as: public static <T> List<T> asList(T... a)

So in your first case, T is int[] and you are passing a single object to the method (i.e. the array), therefore it returns a list of int[].

I think you are mistaking with asList(1, 2, 3, 4, 5) (i.e. 5 items)

like image 22
mprivat Avatar answered Jan 08 '23 07:01

mprivat