[英]interesting behaviour of upper bounded java wildcards
I have example: 我有一个例子:
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));
为什么编译器禁止调用doJob(intList,intList,intList.get(0)); even intList in fact is List type?
甚至intList实际上是List类型?
Well that is because, Ultimately you are doing: 那是因为,最终你在做:
List<? extends Integer> ls = new ArrayList<Integer>();
doJob(ls,ls,ls.get(0));
So ls (or your intList
) is actually a List of an unknown type. 所以ls(或你的
intList
)实际上是一个未知类型的List。 But what you do know, is that this unknown type extends Number
. 但你知道的是,这种未知类型扩展了
Number
。
So when you call doJob
, T
in doJob
becomes this unknown type. 因此,当您调用
doJob
, doJob
中的T
doJob
变为此未知类型。 Your second argument matches as List<? extends Number>
你的第二个参数匹配
List<? extends Number>
List<? extends Number>
is a super type to List<? extends Integer>
List<? extends Number>
是List<? extends Integer>
的超类型 List<? extends Integer>
. List<? extends Integer>
。
As per your third argument, we already know that T
is unknown and you try passing intList.get(0)
. 根据你的第三个参数,我们已经知道
T
是未知的,你尝试传递intList.get(0)
。 Now intList.get
will return ? extends Integer
现在
intList.get
会返回? extends Integer
? extends Integer
, ie another unknown type (which extends Integer). ? extends Integer
,即另一种未知类型(扩展Integer)。 So you try passing an unknown type to a method which expects an unknown type. 因此,您尝试将未知类型传递给期望未知类型的方法。 And two unknown's cant be guaranteed to be equal.
两个不知名的人不能保证是平等的。 Hence the error.
因此错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.