Search code examples
javagenerics

Creating an array of generic collections


Actually, the question should be

Creating an array of generic anything.

Why can't the compiler take care of it?

The following would be flagged as an error - cannot create generic array.

List<MyDTO>[] dtoLists = {new ArrayList<MyDTO>(), anExistingDtoList};

To overcome that, I need to

List<MyDTO>[] dtoLists = (List<MyDTO>[])Array.newInstance(ArrayList.class, 2);
dtoLists[0] = new ArrayList<MyDTO>();
dtoLists[1] = anExistingDtoList;

So, why can't the compiler convert the first case into the second case?

I do realise that generics are compile-time determinate and not run-time determinate, while arrays are run-time determinate and therefore need a determinate type in order to create an array.

What are the technological/logical barriers compiler designers would encounter that would prevent them being able to implement this?

Is the issue purely philosophical, concerning language orthogonality? If so, how would such a behaviour violate language orthogonality?

Is it a question of complexity? Explain the complexity.

I am hoping answers to my question would give me better insight into java compiler behaviour when it concerns generics.

Side note: c'mon stop being trigger happy. The answers Array of Generic List do not answer my question. Why can't compilers spontaneously perform the conversion?


Solution

  • Actually Java does create generic array for varargs, so you can do

    List<MyDTO>[] dtoLists = array(new ArrayList<MyDTO>(), anExistingDtoList);
    
    @SafeVarargs
    static <E> E[] array(E... array)
    {
        return array;
    }
    

    As to why is explicit generic array creation forbidden, it has something to do with type erasure. (The same concern exists in the above solution, but suppressed by @SafeVarargs) However it is debatable; there are different ways to handle the concern, a compiler warning is probably enough. But they chose to outright ban it, probably because arrays are no longer important anyway now that we have generic collections