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

Il-Bhima picture Il-Bhima · Feb 19, 2009 · Viewed 49.7k times · Source

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!

Answer

Guillaume picture Guillaume · Feb 19, 2009

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