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

回眸只為那壹抹淺笑 提交于 2019-11-26 08:36:48

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/4617567/java-arrays-aslist-on-primitive-array-type-produces-unexpected-list-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!