上限 java 通配符的有趣行为

interesting behaviour of upper bounded java wildcards

我有例子:

public static <T extends Number> void doJob(List<T> pr,List<? extends Number> en,T tel){
            // 
            System.out.println(pr.get(0).intValue());

   }

List<? extends Integer> intList=new ArrayList<>();
Integer inval=200;
List<Integer> intList3=new ArrayList<Integer>(Arrays.asList(1,2,3));
doJob(intList3,intList,inval);//it is allowed 
intList=intList3;
doJob(intList,intList,intList.get(0));//IT IS FORBIDDEN

Why does compiler forbid call of doJob(intList,intList,intList.get(0)); even intList in fact is List type?

那是因为,最终你在做:

List<? extends Integer> ls = new ArrayList<Integer>();
doJob(ls,ls,ls.get(0));

So ls(或者你的intList)实际上是一个未知类型的列表。但是您所知道的是,这个未知类型扩展了 Number

所以当你调用doJob时,doJob中的T变成了这个未知类型。您的第二个参数匹配,因为 List<? extends Number>List<? extends Integer> 的超类型。

根据你的第三个参数,我们已经知道 T 是未知的,你尝试传递 intList.get(0)。现在 intList.get 将 return ? extends Integer,即另一种未知类型(扩展 Integer)。因此,您尝试将未知类型传递给需要未知类型的方法。并且不能保证两个未知数相等。因此错误。