javaarraysprimitive-types

Converting an array of objects to an array of their primitive types


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!


Solution

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