Java Arrays.asList on primitive array type produces unexpected List type [duplicate]
Asked Answered
M

2

24

Possible Duplicate:
Arrays.asList() not working as it should?

Apparently the return type of Arrays.asList(new int[] { 1, 2, 3 }); is List<int[]>. This seems totally broken to me. Does this have something to do with Java not autoboxing arrays of primitive types?

Millard answered 6/1, 2011 at 17:7 Comment(1)
int is not an Object, but int[] is.Decline
A
12

The problem is that Arrays.asList takes a parameter of T... array. The only applicable T when you pass the int[] is int[], as arrays of primitives will not be autoboxed to arrays of the corresponding object type (in this case Integer[]).

So you can do Arrays.asList(new Integer[] {1, 2, 3});.

Amador answered 6/1, 2011 at 17:15 Comment(1)
Or simply Arrays.asList(1,2,3);Freakish
D
6

Try:

Arrays.asList(new Integer[] { 1, 2, 3 });

Note Integer instead of int. Collections can contain only objects. No primitive types are allowed. int is not an object, but int[] is, so this is why you get list with one element.

Droplet answered 6/1, 2011 at 17:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.