【问题标题】:Arrays.asList size() returns 1 [duplicate]Arrays.asList size() 返回 1 [重复]
【发布时间】:2014-03-20 09:28:27
【问题描述】:
int length = 10;
int[] theArray = new int[length];

for(int i = 0; i < length; i++){
   theArray[i] = (int) (Math.random()*10)+3;
}
System.out.println("generated array = " + Arrays.toString(theArray));
System.out.println("theArray.length = " + theArray.length);
System.out.println("list size = " + (Arrays.asList(theArray)).size());

打印出来:

generated array = [6, 6, 10, 7, 3, 9, 10, 7, 4, 4]
theArray.length = 10
list size = 1

根据文档 Arrays.asList(theArray) 返回由指定 arrayize 支持的固定大小的列表。 但是为什么我在这里得到列表大小 1 呢?为什么使用列表时没有反映大小。 需要帮助来找出差距和对此的更多见解。

我还检查了我的代码几次,以防有任何愚蠢的差距,还用谷歌搜索了我的观察结果,但没有看到太多的见解。

谢谢,

【问题讨论】:

  • 您正在将数组添加到列表中
  • 你应该使用 Integer[] theArray = new Integer[length] 代替。你看,这个方法签名是 public static List asList(T... a) 并且你不能使用原语作为 T。所以你的 int[] 被“提升”为一个对象并作为单个对象添加进入您的列表。
  • 为了更清楚地了解我的上述评论,如果您尝试将数组添加到列表中,则语法为 List&lt;int[]&gt; list = Arrays.asList(theArray); 。它显示您正在将int[] 添加到列表中,这意味着只有一个对象。因此大小为 1。
  • int[]Integer[]没有自动装箱

标签: java arrays arraylist


【解决方案1】:

那是因为你在 Arrays.asList(..) 中放入了一个对象(一个数组)。

【讨论】:

    猜你喜欢
    • 2016-10-25
    • 1970-01-01
    • 2014-11-01
    • 2017-11-16
    • 2014-12-17
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    相关资源
    最近更新 更多