2015-09-02 68 views
5

我創建一個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 

回答

13

您可以使用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] 
3

使用.add(0)代替。構造函數ArrayList(int capacity)設置初始容量,但不包含初始項目。所以你的清單仍然是空的。

+1

請注意,'Arrays.asList(new int [40])'返回'List '所以你的上面的語句會給編譯時錯誤。 –

9

嘗試Collections.nCopies()

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

OR:

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

doc

+0

這對我來說比較合適。 +1好的一個。 –

+1

請注意,第二個示例返回一個不可變列表 - 這可能是爲什麼它應該包裝在ArrayList中,如第一個示例中所示。 – glaed

+1

這應該是公認的答案! –

0

的Java 8實現:

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

'Collections.nCopies'好得多 – ZhekaKozlov