You cannot create an array from T, because Java does not know at run time what type T is. This is because in Java generic tools are implemented with the type of erase. This means that the compiler dumps most of the information of a general type after everything is fine.
The story is different with arrays because Java needs to know the exact type of T to create the given array, and since such a thing cannot be defined, you cannot create an array of a generic type.
What you can do is provide an instance of the actual array that you want to use, and the Java compiler can guarantee that it has the appropriate type:
public static <T> void fillWith(T[] destiny, List<? extends T> source){ for(int i=0; i<= destiny.length; i++){ destiny[i] = source.get(i); } }
The java.utils.Arrays.copy method offers an alternative, carefully using generalizations and reflections, which you can use as a reference for what you want to do.
public static <T> T[] copyOf(T[] original, int newLength) { return (T[]) copyOf(original, newLength, original.getClass()); } public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) { T[] copy = ((Object)newType == (Object)Object[].class) ? (T[]) new Object[newLength] : (T[]) Array.newInstance(newType.getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; }
Edwin dalorzo
source share