Java Generic List>

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

How come in java we cannot do:

List> aList = new ArrayList>();

Even though thi

5条回答
  •  既然无缘
    2020-11-30 02:56

    In Java, if Car is a derived class of Vehicle, then we can treat all Cars as Vehicles; a Car is a Vehicle. However, a List of Cars is not also a List of Vehicles. We say that List is not covariant with List.

    Java requires you to explicitly tell it when you would like to use covariance and contravariance with wildcards, represented by the ? token. Take a look at where your problem happens:

    List> l = new ArrayList>();
    //        ----------------                          ------
    // 
    // "? extends Number" matched by "Number". Success!
    

    The inner List works because Number does indeed extend Number, so it matches "? extends Number". So far, so good. What's next?

    List> l = new ArrayList>();
    //   ----------------------                    ------------
    // 
    // "List" not matched by "List". These are
    //   different types and covariance is not specified with a wildcard.
    //   Failure.
    

    However, the combined inner type parameter List is not matched by List; the types must be exactly identical. Another wildcard will tell Java that this combined type should also be covariant:

    List> l = new ArrayList>();
    

提交回复
热议问题