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.
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
.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With