Co Codes
Co Codes

Reputation: 3

java.lang.ArrayStoreException storing Integer in Integer array

Why am I getting this exception?

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

I am creating an Integer array and passing in Integer values. Why then, when I create a new instance of the same type of array, am I unable to assign integer values to it?

@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);
}

Upvotes: 0

Views: 140

Answers (1)

LppEdd
LppEdd

Reputation: 21172

The main issue is this bit of code

a.getClass()

What it will return is not the class of the component of the array, but the array itself, e.g.

[Ljava.lang.Integer

See the [L prefix. You need to use

a.getClass().getComponentType()

As Array#newInstance accepts the component type

newInstance(Class<?> componentType, int length)

Upvotes: 1

Related Questions