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:

 Java |  copy |? 
    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;
    }
 

2 comments to Primitive Array to Object[]

  • B

    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;
    }

    • Uwe Schaefer

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

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>