这段代码
static void writeTo(List<? super Apple> apples) {
apples.add(new Apple());
apples.add(new Jonathan());
}
这段代码的作者声明
The argument apples is a List of some type that is the base type of Apple; thus you know that it is safe to add an Apple or a subtype of Apple. Since the lower bound is Apple,
Jonathan 是 Apple 的子类。
但是当我尝试这个的时候
List<Jonathan> loj = new ArrayList<Jonathan>();
listSuper(loj);
它给了我这个错误
The method listSuper(List<? super Apple>) in the type Basket<T> is not applicable for the arguments (List<Jonathan>)
listSuper
看起来像这样
static void listSuper (List<? super Apple> cont) {}
两者有何不同?
此外,让我对我发布的第一个代码感到困惑的是 我想 ? super T 的意思是T的任意基类型。但是从表面上看,他添加了T的子类型。我很困惑。
最佳答案
List<? super Apple>
表示 List
你可以添加一个Apple
到(并且由于 Jonathan
是一个 Apple
,您也可以将 Jonathan
放入该类型的 List
中)。
可以是List<Apple>
, List<Fruit>
或 List<Object>
, 但不是 List<Jonathan>
,因为你不能随意放置 Apple
进入List<Jonathan>
.如您所见,在本例中为 ?
可以是 Apple
或其任何父类(super class)。
List<? extends Apple>
表示 List
你可以获得Apple
从。可以是List<Apple>
或 List<Jonathan>
, 但不是 List<Fruit>
, 自 List<Fruit>
不保证只包含 Apple
这个解释被称为“生产者 - extends
,消费者 - super
”规则:如果参数作为元素的消费者,它应该用 super
声明。 ,反之亦然。
关于java - 为什么不允许这样使用泛型和通配符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12301670/