【发布时间】: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<int[]> list = Arrays.asList(theArray);。它显示您正在将int[]添加到列表中,这意味着只有一个对象。因此大小为 1。 -
从
int[]到Integer[]没有自动装箱