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.

fleetC0m
  • 231
  • 3
  • 12
  • possible duplicate of [How to: generic array creation](http://stackoverflow.com/questions/529085/how-to-generic-array-creation) – Maxim Efimov Apr 16 '14 at 02: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. – Obicere Apr 16 '14 at 02:25
  • @Obicere This is a different question. I need an array of lists of some object. – fleetC0m Apr 16 '14 at 02:28
  • @MaximEfimov No it's not. See my edit. – fleetC0m Apr 16 '14 at 02:33

2 Answers2

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.

Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683
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.

newacct
  • 110,405
  • 27
  • 152
  • 217