tags:

views:

4211

answers:

4

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()]);
+10  A: 

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

Jon Skeet
Now I have my own primitive conversion utility! yay Jon!
masher
+10  A: 

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.

Björn
Note that this approach will make two complete copies of the sequence: one Integer[] created by toArray, and one int[] created inside toPrimitive. The other answer from Jon only creates and fills one array. Something to consider if you have large lists, and performance is important.
paraquat
+1  A: 

using Dollar should be quite simple:

List<Integer> list = $(5).toList(); // the list 0, 1, 2, 3, 4  
int[] array = $($(list).toArray()).toIntArray();

I'm planning to improve the DSL in order to remove the intermediate toArray() call

dfa
A: 

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: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/ArrayUtils.html#toPrimitive%28java.lang.Integer[],%20int%29

Andrew F.
It bewilders me that anyone would need to depend on a 3rd party lib to do something as easy and basic as this. In fact, I would say it edges on being irresponsible.
mmattax
I do agree with the previous commenter. Not only do you drag in Apache Commons, but it easily translates into a large set of transitive dependencies that also need to be dragged in. Recently I could remove an amazing # of dependencies by replacing one line of code :-( Dependencies are costly and writing basic code like this is good practice
Peter Kriens