我希望通过ArrayQueue通过E[] toArray(E[] a)填充外部数组中的元素,但不知怎么它会将ArrayStoreException抛到第一个System.arraycopy方法中。我想知道如何解决这个问题,更重要的是我要知道为什么会抛出这个异常。
这是我的密码:
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;
}这是外部方法:
String[] words = q.toArray(new String[2]);耽误您时间,实在对不起。
发布于 2016-03-12 21:48:47
我怀疑这个异常实际上并不发生在您指出的行中,而是在稍后的System.arraycopy中。
问题是,当您只想传递元素类型时,对Array.newInstance的调用传递数组类型。换句话说,您是在说“给我一个具有元素类型String[]的新数组”,其中您真正想说的是“给我一个具有元素类型String的新数组”。
要做到这一点,只需使用getClass().getComponentType()。演示--这是一个简单但完整的问题示例,如果您删除了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;
}
}发布于 2016-03-12 21:47:09
a.getClass()不返回E,它将返回E的数组(因为a是数组)。这就是为什么你在这个任务上有困难
https://stackoverflow.com/questions/35963640
复制相似问题