我目前正在开发 Java Collection Framework ,并创建了一个大小为 10 的列表,但程序仍然提示我列表大小为 0
,此外,如果列表已处理,则会抛出 IndexOfBoundException
当然
我已经搜索过这个问题,但我不知道为什么它会发生在我身上
int size =sc.nextInt();
List<Integer> list = new ArrayList<Integer>(size);
System.out.println(list+" "+list.size());
我期望输出为 [0,0,0,0,0,0,0,0,0,0] 10 但输出为 [] 0 。
最佳答案
要将List
初始化为具有默认值的给定大小,您可以使用nCopies
:
List<Integer> list = new ArrayList<>(Collections.nCopies(size,0));
现在您的 println
语句将输出:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 10
(假设大小
为10
)。
关于java - 为什么 ArrayList 没有使用运行时输入进行初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57087692/