Generic type for Arraylist of Arraylists

前端 未结 5 655
长情又很酷
长情又很酷 2021-01-02 12:54

In normal array list initialization, We used to define generic type as follows,

List list1 = new ArrayList();

B

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-02 13:33

    You are talking about an array of lists (ArrayLists to be more specific). Java doesn't allow generic array generation (except when using wildcards, see next paragraph). So you should either forget about using generics for the array, or use a list instead of an array (many solutions proposed for this).

    Quote from IBM article:

    Another consequence of the fact that arrays are covariant but generics are not is that you cannot instantiate an array of a generic type (new List[3] is illegal), unless the type argument is an unbounded wildcard (new List< ?>[3] is legal).

提交回复
热议问题