1

EDIT: This is NOT a duplicate of the above question. The original question concerns a list whose type is unknown at compile time. This question concerns an array like construct of a generic list. For example the above solution of final E[] a = (E[]) Array.newInstance(c, s); won't work because I can not obtain List<MyClass>.class And also you can't cast from Object[] to List<MyClass>[]

What is the idiomatic way to deal with an array like construct of generic type? For example, I want an array of List<MyClass>. ArrayList<List<MyClass>> myClassArray won't work directly because I need to be able to do things like myClassArray.set(5, myClassObj) even when the myClassArray.size() is 0. Initialize it with

for(int i = 0; i < mySize; i ++){
    myClassArray.add(null)
}

works but it's ugly.

List<MyClass> myClassArray[] won't work either because you can't create a generic array. So what is the most idiomatic way to achieve my goal? The size of array won't change once created.

4
  • possible duplicate of How to: generic array creation Commented Apr 16, 2014 at 2:25
  • A List does not sound like the right data type for that. The only way you could change the element at index 5, which you tried to do, is if there are at least 6 objects in the list already. Sounds like you just need an array. Commented Apr 16, 2014 at 2:25
  • @Obicere This is a different question. I need an array of lists of some object. Commented Apr 16, 2014 at 2:28
  • @MaximEfimov No it's not. See my edit. Commented Apr 16, 2014 at 2:33

2 Answers 2

2

Create your own class to simulate an array.

class Array<T> {
    final Object[] data;

    public Array(int size) {
        data = new Object[size];
    }

    public void set(int index, T datum) {
        data[index] = datum;
    }

    @SuppressWarnings("unchecked")
    public T get(int index) {
        return (T) data[index];
    }
}

Since you control the access to the underlying array, you know that the elements in there will all be of type T.

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

Comments

0

The usual way is

List<MyClass>[] myClassArray = new List[size];

The reason why the type of array of parameterized types is "unsafe" is very obscure (because arrays are supposed to check at runtime when you put something into it that it's an instance of the component type, but it's not possible to actually check the parameter for a parameterized type) and not relevant for your purposes.

1 Comment

why not just write List<MyClass>[] myClassArray = new List[size]; ?a lot shorter

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.