Why is this generics array creation not working as expected?

generics, java

Solution

The type of `A` is `java.lang.String[]`, rather than `java.lang.String`.

You want the component type of the array, rather than the array type itself.

Use this line instead:

T[] temp = (T[]) Array.newInstance(A.getClass().getComponentType(), A.length);

and the code runs fine.

Problem

I have the following code where I'm creating an array and trying to store objects in it. At run time, I get an `ArrayStoreException`. ``` import java.lang.reflect.Array; public class GenericsArrayCreation<T> { public static <T> void Test(T[] A){ @SuppressWarnings("unchecked") T[] temp = (T[]) Array.newInstance(A.getClass(), A.length); for(int i = 0;i<temp.length;i++){ temp[i] = A[i]; System.out.println(temp[i].toString()); } } public static void main(String[] args){ String[] strs = {"a", "b", "c"}; GenericsArrayCreation.Test(strs); } } ``` I somehow understand that this is because of the statement ``` T[] temp = (T[]) Array.newInstance(A.getClass(), A.length); ``` Why is this wrong? `A.getClass()` at runtime returns a `String`, so `temp` should be an array of strings. In that case, why is the assignment `temp[i] = A[i]` not working?

Original source