Java Generic List>

后端 未结 5 1814
别那么骄傲
别那么骄傲 2020-11-30 02:06

How come in java we cannot do:

List> aList = new ArrayList>();

Even though thi

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 02:55

    Your statement does not compile because List is not the same type as List. The former is a supertype of the latter.

    Have you tried this? Here I'm expressing that the List is covariant in its type argument, so it will accept any subtype of List (which includes List).

    List> aList = new ArrayList>();
    

    Or even this. Here the type parameter for the ArrayList on the right-hand side is the same as the type parameter on the left-hand side, so variance is not an issue.

    List> aList = new ArrayList>();
    

    You should be able to just say

    List> aList = new ArrayList>();
    

    I tend to avoid the ? type wildcard whenever possible. I find that the expense incurred in type annotation is not worth the benefit.

提交回复
热议问题