0

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);
}
1
  • Use java.util.Arrays#copyOf(U[], int, java.lang.Class<? extends T[]>) Commented Mar 7, 2019 at 16:57

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.