Generic Arrays

Arrays are not always easy to handle in Java. Especially editing and copying when using Java 5 generics is difficult. Arrays.asList() and List.toArray() offer some comfort but sometimes this is not enough.

List.toArray() return a correct typed array, when a array is passed as parameter. This parameter will also used as target. If you want to create a new array in a generic way, you can only use Array.newInstance(). The problem is the first parameter , the component type. If you have any array of the desired type, you can use Class.getComponentType():

@SuppressWarnings("unchecked")
private static E[] createArrayAs(E[] values, int size)
{
return (E[]) Array.newInstance(values.getClass().getComponentType(), size);
}


The cast to E[] is necessary. It is a good idea to extract such a call in a single method to suppress the unchecked warning for this single call.