Exception when using shared arrays

I have an ArrayStoreException that I do not understand in the following scenario:

file List.java:

import java.lang.reflect.Array;
class List<K> {
    K[] _list;
    K _dummy;
    int _size, _index;

    public List(int size) {
        _size = size;
        _index = 0;
        Class<?> cls = getClass();

        // as following is not allowed
        // _list = new K[size]; -->  cannot create a generic array of K
        // I'm doing the following instead
        _list = (K[])Array.newInstance(cls,size);
    }

    public void add(K obj) {
        _list[_index++] = obj;  // HERE THE EXCEPTION
                        //      java.lang.ArrayStoreException ??

        // IF I ASSIGN _dummy INSTEAD
        _list[_index++] = _dummy;   // NO ERROR
    }
} // class List

mainLists.java file:

public class mainLists {    
    public static void main(String[] args) {        
        List<String> list = new List<String>(5);
        list.add("test");
    }
}

What the docs say about ArrayStoreException: "Thrown to indicate that an attempt was made to save the wrong type of an object into an array of objects"

but am I passing a "test type" of type String to add () no?

what is the problem?

THX

Chris

+3
source share
2 answers

Your array is a List array, not a K array, since you create it with

Array.newInstance(cls,size);

where is clsinitialized by the character

Class<?> cls = getClass();

which returns the current class of the object, i.e. class this.

You can just use Object[].

+4
source

Class<?> cls = getClass(); (this), , List, Strings.

, , , , Class List, , K.

public List(int size, Class<K> clazz)
+2