开发者

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

开发者 https://www.devze.com 2023-02-03 02:05 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: Arrays.asList() not working as it should?
This question already has answers here: Closed 12 years ago.

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?


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});.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号