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
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments