Cast to generic type causing ArrayStoreException in Java

167 views Asked by At

I am making a class that contains an instance variable of type Object[] that is named array. This class includes a method that returns a T[], where T is a generic. The method should copy the contents of array on to the array to be returned. The relevant code looks like this:

@SuppressWarnings("unchecked")
T[] arr = (T[])Array.newInstance(a.getClass(), array.length);
for (int i = 0; i < array.length; i++) {
    @SuppressWarnings("unchecked")
    T temp = (T)array[i];
    arr[i] = temp;
}
return arr;

In the above snippet, a is yet another array that was passed as a parameter.

The issue is, when I call the method, it throws an ArrayStoreException. I'm not sure why it is doing that because I am casting the initial value to type T before storing it in the array which is of type T[], so the types match. Why is is still throwing the exception?

2

There are 2 answers

0
k5_ On BEST ANSWER

With that code you create an T[][] because a.getClass() is Class<T[]>.

What you want is a.getClass().getComponentType(), thats the actual Class<T>

So:

@SuppressWarnings("unchecked")
T[] arr = (T[])Array.newInstance(a.getClass().getComponentType(), array.length);
for (int i = 0; i < array.length; i++) {
    @SuppressWarnings("unchecked")
    T temp = (T)array[i];
    arr[i] = temp;
}
return arr;

Or you can use the jre method

Arrays.copyOf(array, array.length); // creates a new array and copies the content
0
imp On

You need to check the relationship between the type of array[i] and T, because they don't necessarily have an extended relationship.