Primitive Array to Object[]

If ever you face the need of ‘boxing’ the elements of a primitive array into an array of Objects, this might be handy:

    public static Object[] convertPrimitiveArray(final Object array)
    {
        final int arrayLength = Array.getLength(array);
        final Object[] result = (Object[]) Array.newInstance(Object.class, arrayLength);
        for (int i = 0; i < arrayLength; i++)
        {
            Array.set(result, i, Array.get(array, i));
        }
        return result;
    }
About these ads

2 thoughts on “Primitive Array to Object[]

  1. You can generify the method to have the wrapper return type (at the cost of unchecked cast).


    public static T[] convertPrimitiveArray(final Object array, Class wrapperClass) {
    final int arrayLength = Array.getLength(array);
    final T[] result = (T[]) Array.newInstance(wrapperClass, arrayLength);
    for (int i = 0; i < arrayLength; i++) {
    Array.set(result, i, Array.get(array, i));
    }
    return result;
    }

    • sure, but then it´d be public static T[] convertPrimitiveArray(final Object array, Class wrapperClass)
      but it throws RTEs at you anyway :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s