Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Arrays.asList(int[]) can return List<int[]>?

Tags:

java

While doing simple program I noticed this issue.

int[] example = new int[10];
List<Integer> exampleList = Arrays.asList(example);// Compilation error here  

Compilation error is returned as cannot convert from List<int[]> to List<Integer>. But List<int> is not permitted in java so why this kind of compilation error?

I am not questioning about autoboxing here I just wondered how Arrays.asList can return List<int[]>.

asList implementation is

public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}

So it is treating int[] as T that is why this is happening.

like image 737
Amit Deshpande Avatar asked Aug 18 '12 17:08

Amit Deshpande


2 Answers

There is no automatic autoboxing done of the underlying ints in Arrays.asList.

  • int[] is actually an object, not a primitive.

  • Here Arrays.asList(example) returns List<int[]>. List<int> is indeed invalid syntax.

  • You could use:

    List<Integer> exampleList = Arrays.asList(ArrayUtils.toObject(array));

    using Apache Commons ArrayUtils.

like image 188
Reimeus Avatar answered Sep 18 '22 15:09

Reimeus


Arrays.asList(...) works perfectly to transform an array of objects into a list of those objects.

Also, Arrays.asList(...) is defined in Java 5 with a varag construct, or, in order words, it can accept an undefined number of parameters in which case it will consider all of those parameters as members of an array and then return a List instance containing those elements.

List<Object> objList = Arrays.asList(obj1, obj2, obj3);

That means you can create a list with a single element:

List<Object> objList = Arrays.asList(obj1);

Since List<int> is not permitted in Java, when you use a int[] array as parameter for Arrays.asList it will consider it as the single element of a list instead of an array of int. That's because arrays are objects by themselves in Java while an int (and any other primitive) is not.

So, when converting an array of primitives, Arrays.asList will try to return a list of primitive arrays:

List<int[]> intArrayList = Arrays.asList(new int[]{ 1, 2, 3 });
like image 32
Alonso Dominguez Avatar answered Sep 18 '22 15:09

Alonso Dominguez