3

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

2 Answers 2

4

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[].

Sign up to request clarification or add additional context in comments.

Comments

2

Class<?> cls = getClass(); will use current instance (this) to get Class object so later you are creating array of Lists 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)

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.