Creating an array of generic collections

前端 未结 3 542
情话喂你
情话喂你 2021-02-07 03:20

Actually, the question should be

Creating an array of generic anything.

Why can\'t the compiler take care of it?

The following would be

3条回答
  •  日久生厌
    2021-02-07 03:46

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

    List[] dtoLists = array(new ArrayList(), anExistingDtoList);
    
    @SafeVarargs
    static  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

提交回复
热议问题