I would like fill an external array with the elements of my ArrayQueue via E[] toArray(E[] a)
, but somehow it throws ArrayStoreException
at the first System.arraycopy
method. I would like to know how to solve this issue, and even more important for me to know why this exception is thrown.
Here's my code:
public E[] toArray(E[] a)
{
if(a.length != size)
a=(E[])Array.newInstance(a.getClass(), size);
if(head<tail)
System.arraycopy(elementData, head, a, 0, tail-head); // ArrayStoreException
else
{
System.arraycopy(elementData, head, a, 0, capacity-head);
System.arraycopy(elementData, 0, a, capacity-head, tail);
}
return a;
}
This is the external method:
String[] words = q.toArray(new String[2]);
Thanks for your time.
I suspect the exception doesn't actually happen on the line you've indicated, but later, in System.arraycopy
.
The problem is that your call to Array.newInstance
passes in the array type, when you only want to pass in the element type. In other words, you're saying "Give me a new array with an element type String[]
" where you really want to say "Give me a new array with an element type String
".
To do this, just use getClass().getComponentType()
. Demo which is a simpler but complete example of the problem, if you remove getComponentType()
:
import java.lang.reflect.*;
public class Test {
public static void main(String[] args) {
String[] original = new String[] { "x" };
String[] x = Test.<String>toArray(original);
}
public static <E> E[] toArray(E[] a) {
E[] copy = (E[]) Array.newInstance(a.getClass().getComponentType(), a.length + 1);
System.arraycopy(a, 0, copy, 0, a.length);
return copy;
}
}
See more on this question at Stackoverflow