views:

1698

answers:

5

If you have an array of java objects which have a primitive type (for example Byte, Integer, Char, etc). Is there a neat way I can convert it into an array of the primitive type? In particular can this be done without having to create a new array and loop through the contents.

So for example, given

Integer[] array

what is the neatest way to convert this into

int[] intArray

Unfortunately, this is something we have to do quite frequently when interfacing between Hibernate and some third party libraries over which we have no control. It seems this would be a quite common operation so I would be surprised if there's no shortcut.

Thanks for your help!

+11  A: 

Unfortunately, there's nothing in the Java platform that does this. Btw, you also need to explicitly handle null elements in the Integer[] array (what int are you going to use for those?).

Zach Scrivena
Good point about the nulls. For my purposes I would have accepted an exception being thrown if one of the entries is null, the same way an NullPointerException is thrown when you unbox an object.
Il-Bhima
+1  A: 

In particular can this be done without having to create a new array and loop through the contents.

You can't convert an array of Integer to int (i.e. you can't change the type of the elements of an array) in Java. So you either must create a new int[] array and copy the value of the Integer objects into it or you can use an adapter:

class IntAdapter {
    private Integer[] array;
    public IntAdapter (Integer[] array) { this.array = array; }
    public int get (int index) { return array[index].intValue(); }
}

This can make your code a little more readable and the IntAdapter object will only consume a few bytes of memory. The big advantage of an adapter is that you can handle special cases here:

class IntAdapter {
    private Integer[] array;
    public int nullValue = 0;
    public IntAdapter (Integer[] array) { this.array = array; }
    public int get (int index) { 
        return array[index] == null ? nullValue : array[index].intValue();
    }
}

Another solution is to use Commons Primitives which contains lots of predefined adapters. In your case, have a look at ListIntList.

Aaron Digulla
A: 

Or just do it the easy way if you gonna do it only once. But you haven't talked about Integer!=null case.

    //array is the Integer array
    int[] array2 = new int[array.length];
    int i=0;
    for (Integer integer : array) {
        array2[i] = integer.intValue();
        i++;
    }
Jens Jansson
+17  A: 

Once again, commons-lang is your friend. They provide ArrayUtils.toPrimitive() which does exactly what you need. You can specify how you want to handle nulls.

Guillaume
A: 

using Dollar is simple as:

Integer[] array = ...;
int[] primitiveArray = $(array).toIntArray();
dfa