How to convert an ArrayList containing Integers to

2018-12-31 20:09发布

I'm trying to convert an ArrayList containing Integer objects to primitive int[] with the following piece of code, but it is throwing compile time error. Is it possible to convert in Java?

List<Integer> x =  new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);

12条回答
路过你的时光
2楼-- · 2018-12-31 20:24

Apache Commons has a ArrayUtils class, which has a method toPrimitive() that does exactly this.

import org.apache.commons.lang.ArrayUtils;
...
    List<Integer> list = new ArrayList<Integer>();
    list.add(new Integer(1));
    list.add(new Integer(2));
    int[] intArray = ArrayUtils.toPrimitive(list.toArray(new Integer[0]));

However, as Jon showed, it is pretty easy to do this by yourself instead of using external libraries.

查看更多
闭嘴吧你
3楼-- · 2018-12-31 20:27

You can convert, but I don't think there's anything built in to do it automatically:

public static int[] convertIntegers(List<Integer> integers)
{
    int[] ret = new int[integers.size()];
    for (int i=0; i < ret.length; i++)
    {
        ret[i] = integers.get(i).intValue();
    }
    return ret;
}

(Note that this will throw a NullPointerException if either integers or any element within it is null.)

EDIT: As per comments, you may want to use the list iterator to avoid nasty costs with lists such as LinkedList:

public static int[] convertIntegers(List<Integer> integers)
{
    int[] ret = new int[integers.size()];
    Iterator<Integer> iterator = integers.iterator();
    for (int i = 0; i < ret.length; i++)
    {
        ret[i] = iterator.next().intValue();
    }
    return ret;
}
查看更多
只若初见
4楼-- · 2018-12-31 20:27

Google Guava

Google Guava provides a neat way to do this by calling Ints.toArray.

List<Integer> list = ...;
int[] values = Ints.toArray(list);
查看更多
与君花间醉酒
5楼-- · 2018-12-31 20:28

This code segment is working for me, try this

Integer[] arr = x.toArray(new Integer[x.size()]);
查看更多
冷夜・残月
6楼-- · 2018-12-31 20:29
Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);

access arr like normal int[].

查看更多
琉璃瓶的回忆
7楼-- · 2018-12-31 20:30

It bewilders me that we encourage one-off custom methods whenever a perfectly good, well used library like Apache Commons has solved the problem already. Though the solution is trivial if not absurd, it is irresponsible to encourage such a behavior due to long term maintenance and accessibility.

Just go with Apache Commons

查看更多
登录 后发表回答