2011-11-21 56 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); 
相关问题