Java Generic List>

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

How come in java we cannot do:

List> aList = new ArrayList>();

Even though thi

5条回答
  •  醉酒成梦
    2020-11-30 02:54

    You should definitely use the ? type wildcard when appropriate, do not avoid it as a general rule. For example:

    public void doThingWithList(List> list);
    

    allows you to pass a List or a List.

    public void doThingWithList(List> list);
    

    allows you to only pass arguments declared as List. A small distinction, yes, but using the wildcard is powerful and safe. Contrary to how it may seem, a List is not a subclass, or is not assignable, from List. Nor is List a subclass of List, which is why the code above does not compile.

提交回复
热议问题