java.lang.ArrayStoreException将Integer存储在Integer数组中

时间:2019-03-07 16:50:19

标签: java arrays

为什么会出现此异常?

java.lang.ArrayStoreException: java.lang.Integer
at MyLinkedList.toArray(MyLinkedList.java:94)
at MyLinkedListTest.toArray_ReturnGenericArray(MyLinkedListTest.java:80)

我正在创建一个Integer数组并传递Integer值。为什么然后,当我创建相同类型数组的新实例时,我无法为其分配整数值?

@Override
public <T1> T1[] toArray(T1[] a) {
    if (a.length < size) {
        a = (T1[]) java.lang.reflect.Array.newInstance(a.getClass(), size);
    }
    Node<T> current = head;
    int i = 0;
    Object[] result = a;
    while (current != null) {
        result[i] = current.value;
        i++;
        current = current.next;
    }
    // if array has room to spare set element immediately following end of list to null
    if (a.length > i) {
        a[i] = null;
    }
    return a;
}

@Test
void toArray_ReturnGenericArray() {
    Integer[] array2 = linkedList.toArray(new Integer[4]);
    assertEquals(1, array2[0]);
    assertEquals(2, array2[1]);
    assertEquals(3, array2[2]);
    assertEquals(4, array2[3]);
    assertEquals(5, array2[4]);
    assertEquals(5, array2.length);
}

1 个答案:

答案 0 :(得分:1)

主要问题是这段代码

a.getClass()

返回的不是数组 component 的类,而是数组本身,例如

[Ljava.lang.Integer

请参见[L前缀。您需要使用

a.getClass().getComponentType()

Array#newInstance接受组件类型

newInstance(Class<?> componentType, int length)