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
.
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:
Integer[]
in the first place, orThe 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)
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