What is the difference between <? extends Base> and ?

前端 未结 4 1533
温柔的废话
温柔的废话 2021-02-01 03:24

In this example:

import java.util.*;

public class Example {
    static void doesntCompile(Map> map) {}
    static &l         


        
4条回答
  •  走了就别回头了
    2021-02-01 04:20

    Simplied example of demonstration. Same example can be visualize like below.

    static void demo(List> lst) {} // doesn't work
    static void demo(List> lst) {} // works
    demo(new ArrayList()); // works
    demo(new ArrayList()); // works for subtype too
    
    public static class Pair {}
    public static class SubPair extends Pair {}
    

    List> is a multi-level wildcards type whereas List is a standard wildcard type .

    Valid concrete instantiations of the wild card type List include Number and any subtypes of Number whereas in case of List> which is a type argument of type argument and itself has a concrete instantiation of the generic type.

    Generics are invariant so Pair wild card type can only accept Pair>. Inner type ? extends Number is already covariant. You have to make the enclosing type as covariant to allow covariance.

提交回复
热议问题