我創建一個ArrayList
其尺寸爲40
用來初始化用零
ArrayList<Integer> myList= new ArrayList<>(40);
我怎麼能初始化myList
用零0
的ArrayList?我想這
for(int i=0; i<40; i++){
myList.set(i, 0);
}
,但我得到
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
我創建一個ArrayList
其尺寸爲40
用來初始化用零
ArrayList<Integer> myList= new ArrayList<>(40);
我怎麼能初始化myList
用零0
的ArrayList?我想這
for(int i=0; i<40; i++){
myList.set(i, 0);
}
,但我得到
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
您可以使用Collections.fill(List<? super T> list,T obj)
方法用零填充您的列表。在你的情況下,你在這裏設置new ArrayList<>(40)
40
不是列表的長度,而是初始容量。您可以使用數組來構建您的列表,其中包含全零。簽出一段代碼。
Integer [] arr = new Integer[40];
ArrayList<Integer> myList= new ArrayList<>(Arrays.asList(arr));
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]
使用.add(0)
代替。構造函數ArrayList(int capacity)
設置初始容量,但不包含初始項目。所以你的清單仍然是空的。
有你可以有相當添加不是設置。 myList.add
將工作。您只能在該特定索引上已有條目的情況下進行設置。 set
方法只會替換該索引處的內容。
Check api documentation for set method here
的Java 8實現:
ArrayList<Integer> list = IntStream.of(new int[40])
.boxed()
.collect(Collectors.toList());
'Collections.nCopies'好得多 – ZhekaKozlov
請注意,'Arrays.asList(new int [40])'返回'List'所以你的上面的語句會給編譯時錯誤。 –