用零初始化 arrayList

Initialize an arrayList with zeros

我正在创建一个 ArrayList,它的大小是 40

ArrayList<Integer> myList= new ArrayList<>(40);

如何用零 0 初始化 myList ?我试过这个

for(int i=0; i<40; i++){
   myList.set(i, 0);
}

但我得到

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

改用.add(0)ArrayList(int capacity) 构造函数设置初始容量,但不设置初始项。所以你的列表还是空的。

这里可以用Collections.fill(List<? super T> list,T obj) method to fill your list with zeros. In your case you are setting new ArrayList<>(40) 40不是列表的长度而是初始容量。您可以使用数组来构建包含所有零的列表。签出以下代码。

ArrayList<Integer> myList= new ArrayList<>(Arrays.asList(new Integer[40]));
Collections.fill(myList, 0);//fills all 40 entries with 0"
System.out.println(myList);

输出

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

在那里你可以添加而不是设置。 myList.add 会起作用。仅当该特定索引上已有条目时才可以设置。 set 方法仅替换该索引处的内容。
Check api documentation for set method here

尝试 Collections.nCopies():

ArrayList<Integer> myList = new ArrayList<Integer>(Collections.nCopies(40, 0));

或:

List<Integer> myList = Collections.nCopies(40, 0);

doc

Java 8 实施:

ArrayList<Integer> list = IntStream.of(new int[40])
                    .boxed()
                    .collect(Collectors.toList());