How to Create a Generic Java Array Without Pain and Tears

The Generic Java Array Problem

With Java, generics and arrays do not play together well so attempting to create a Generic Java Array is a very non intuitive process.  For example, the following code would appear, on initial inspection, to be viable:

public static  T[] convertToNumeric(String[] values)
{
   T[] numbers = new T[values.length];
   // do some magic here
   return numbers;
}

Unfortunately, due to the rather broken implementation of generics in Java, creating a generically typed array is never going to work. Basically, Java has no idea what the type actually is at run-time due to an interesting design decision called ‘type erasure’. For all the technicalities, have a look here

There are two advantages with the approach taken:

  • The JVM does not require extending to handle run-time dynamic class types
  • Generics incur no run-time overhead

A Solution

I am hesitant to say ‘the solution’ as this issue can be approached from a number of directions. A standard hack I use to get around this is to pass into a method, the Class of the generic item. For example:

public static  T[] convertToNumeric(Class<T[]> clazz, String[] values)
{
   T[] numbers =
      clazz.cast(Array.newInstance(clazz.getComponentType(), values.length));
   // do some magic here
   return numbers;
}

Hardly an elegant solution but it does work at the expense of the extra clazz parameter.

For a full discussion on Java Generics, the Wikipedia article is worth a read.