【问题标题】:Java Arrays.asList on primitive array type produces unexpected List type [duplicate]原始数组类型上的 Java Arrays.asList 产生意外的列表类型 [重复]
【发布时间】:2011-01-06 17:07:22
【问题描述】:

可能重复:
Arrays.asList() not working as it should?

显然Arrays.asList(new int[] { 1, 2, 3 }); 的返回类型是List<int[]>。这对我来说似乎完全崩溃了。这是否与 Java 不自动装箱原始类型数组有关?

【问题讨论】:

  • int 不是 Object,但 int[] 是。

标签: java arrays primitive autoboxing


【解决方案1】:

问题是Arrays.asList 的参数是T... array。当您传递int[] 时,唯一适用的Tint[],因为基元数组不会自动装箱为相应对象类型的数组(在本例中为Integer[])。

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

【讨论】:

  • 或者干脆Arrays.asList(1,2,3);
【解决方案2】:

试试:

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

注意 Integer 而不是 int。集合只能包含对象。不允许使用原始类型。 int 不是对象,但 int[] 是,所以这就是为什么你会得到一个包含一个元素的列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 2019-05-23
    • 2015-02-15
    • 2018-08-09
    • 2017-06-14
    相关资源
    最近更新 更多