I'm having an ArrayStoreException which I don't understand in 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'S THE EXCEPTION
// java.lang.ArrayStoreException ??
// IF I ASSIGN _dummy INSTEAD
_list[_index++] = _dummy; // NO ERROR
}
} // class List
file mainLists.java:
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 has been made to store the wrong type of object into an array of objects"
but I'm passing a String type "test" to the method add() no?
what is the problem here?
thx
CHris