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?
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