[英]Lower bounded wildcard method
Could anyone please let me understand why this piece of code is getting compiler error:任何人都可以让我理解为什么这段代码会出现编译器错误:
List<? super A> superList = new ArrayList<>();
superList.add(new Object());
While this one is perfectly correct:虽然这是完全正确的:
setSuper(new ArrayList<Object>());
public void superMethod(List<? super A> list) {
//...
}
I understand that lower bound narrows available types to A or their descendants, but why this is fine for compiler when it comes to methods arguments?我知道下限将可用类型缩小到 A 或其后代,但是为什么在方法参数方面这对编译器来说很好?
An ArrayList<Object>
is a valid value of type List<? super A>
ArrayList<Object>
是List<? super A>
List<? super A>
. List<? super A>
。
An ArrayList<A>
is also a valid value of type List<? super A>
ArrayList<A>
也是List<? super A>
List<? super A>
. List<? super A>
。
But you can't add new Object()
to an ArrayList<A>
.但是您不能将
new Object()
添加到ArrayList<A>
。 So not all List<? super A>
所以不是所有的
List<? super A>
List<? super A>
values can add an object, so the compiler correctly errors. List<? super A>
values 可以添加一个对象,所以编译器正确出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.