如何将元素(或转换为Integer ArrayList)添加到整数数组

时间:2011-11-21 22:08:52

标签: java arrays arraylist integer

这是我有的东西

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);

现在我想将此“列表”转换为数组... e.g:

Integer[] actual= {50,55,98,101};
无论如何怎么办?感谢。

2 个答案:

答案 0 :(得分:6)

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

如果你想要一个int[]数组,你必须循环遍历列表并明确地取消打包每个元素。

下次您正在寻找List的方法时,请参阅http://download.oracle.com/javase/6/docs/api/java/util/List.html

答案 1 :(得分: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);