- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这段代码
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/
我是一名优秀的程序员,十分优秀!