Reputation: 117
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
Upvotes: 3
Views: 80
Reputation: 124275
Class<?> cls = getClass();
will use current instance (this
) to get Class object so later you are creating array of List
s which will not accept Strings
.
Maybe instead of guessing what type of array to create let user pass Class
in List
constructor which will be same as specified K
type.
public List(int size, Class<K> clazz)
Upvotes: 2
Reputation: 692181
Your array is an array of List, and not an array of K, since you instantiate it with
Array.newInstance(cls,size);
where cls
is initialized with
Class<?> cls = getClass();
which returns the current object class, i.e. the class of this
.
You can simply use an Object[]
.
Upvotes: 4