2011-11-21 37 views
1

這裏就是我有如何添加元素(或轉換一個整數的ArrayList)到一個整數數組

ArrayList<Integer> list = new ArrayList<Integer>(); 
    Integer a = 50; 
    Integer b = 55; 
    Integer c = 98; 
    Integer d = 101; 
    list.add(a); 
    list.add(b); 
    list.add(c); 
    list.add(d); 

現在我想這個「清單」轉換成數組... 例如:

Integer[] actual= {50,55,98,101}; 

反正怎麼辦呢?謝謝。

+0

list.toArray(new Integer [0]); –

回答

6
Integer[] array = list.toArray(new Integer[list.size()]); 

如果你想要一個int[]數組,你必須遍歷列表,並明確拆箱每個元素。

請參見http://download.oracle.com/javase/6/docs/api/java/util/List.html下次查找List方法時。

+0

Apache [Commons Lang's](http://commons.apache.org/lang/)[ArrayUtils.toPrimitive](http://commons.apache.org/lang/api-release/org/apache/commons/lang3/ ArrayUtils.html#toPrimitive(java.lang.Integer []))方法可以幫助在包裝數組和基元數組之間進行轉換。 – prunge

+0

問題解決了,非常感謝 – sefirosu

1

Sefirosu,對於另一種解決方案,您也可以使用Arrays.copyOf()Arrays.copyOfRange()

Integer[] integerArray = Arrays.copyOf(list.toArray(), list.toArray().length, Integer[].class); 
Integer[] integerArray = Arrays.copyOfRange(list.toArray(), 0, 4, Integer[].class); 
相關問題