【发布时间】:2018-11-20 22:55:11
【问题描述】:
这可能是一个非常愚蠢的问题,但是我不明白为什么编译器会抱怨和编译。
我有两个非常简单的类:
class A {
}
class B extends A {
}
现在是代码:
//block1
List<A> list = new ArrayList<>();
list.add(new A()); //ok
list.add(new B()); //ok
//block2
List<? extends A> extendList= new ArrayList<>();
extendList.add(new A()); //not ok, why?
extendList.add(new B()); //not ok, why?
//block3
List<? super A> superList = new ArrayList<>();
superList.add(new A()); //ok
superList.add(new B()); //ok. why?
block1 我知道它为什么起作用。
block2,我有<? extends A>,据我了解,该列表将接受类型为A 或A 的子类型的对象,例如B。为什么add() 两条线都失败了?有错误:
Error: no suitable method found for add(A)
method java.util.Collection.add(capture#1 of ? extends A) is not applicable
(argument mismatch; A cannot be converted to capture#1 of ? extends A)
method java.util.List.add(capture#1 of ? extends A) is not applicable
(argument mismatch; A cannot be converted to capture#1 of ? extends A)
block3,我有<? super A>,据我了解,该列表将接受类型为A 或超类型为A 的对象,B 是@987654334 的subType @,为什么add(new B())会编译?
我想我可能误解了super 和extends 关键字,我做了一些谷歌,但我的疑问仍然存在。
oracle通用教程的一句话:(https://docs.oracle.com/javase/tutorial/java/generics/upperBounded.html)
The term List<Number> is more restrictive than List<? extends Number>
because the former matches a list of type Number only, whereas the
latter matches a list of type Number or any of its subclasses.
【问题讨论】:
-
我有一个猜测,但你可以试试
List<? extends A> extendList= new ArrayList<A>();吗?我不认为<>知道如何从 ,而 super A> 表示“A 的任何子类”