Java下限通配符 [英] Java lower bound wildcards

查看:45
本文介绍了Java下限通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力解决这个问题,并且想知道是否有人可以解释这个原因.

I'm struggling to get my head around this and was wondering if someone could explain the reasons for this.

我有三节课:

class Angel {}
class Person extends Angel {}
class Employee extends Person {}

当我尝试执行此代码时

public static void insertElements(List<? super Person> list){
    list.add(new Person());
    list.add(new Employee());
    list.add(new Angel());
}

我得到一个错误:

The method add(capture#5-of ? super Person) in the type List<capture#5-of ? super Person> is not applicable for the arguments (Angel)

我总是阅读文档以表示< ;?super X> 表示任何类型的X或X的超类(因此,在我的情况下,Angel是Person的超类),应该允许吗?显然不是!

I had always read the documentation to mean <? super X > meant any type of X or a superclass of X (so in my case, Angel is a superclass of Person) and should be permitted? Obviously not!

有人有任何简单的例子吗?

Does anyone have any simple examples?

推荐答案

您的直观逻辑说:" List< ;?超级人物> 事物列表,这些事物是Person Person 的超型,因此自然可以在其中添加 Angel ."这种解释是错误的.

Your intuitive logic says "a List<? super Person> is a list of things that are a Person or a supertype of Person, so naturally I can add an Angel into it". That interpretation is wrong.

声明 List< ;?超级人物list 保证 list 的类型允许将任何 Person 的内容添加到列表中.由于 Angel 不是 Person ,因此编译器自然不允许这样做.考虑使用 insertElements(new ArrayList< Person>)调用您的方法.将 Angel 添加到这样的列表中可以吗?绝对不是.

The declaration List<? super Person> list guarantees that list will be of such a type that allows anything that is a Person to be added to the list. Since Angel is not a Person, this is naturally not allowed by the compiler. Consider calling your method with insertElements(new ArrayList<Person>). Would it be okay to add an Angel into such a list? Definitely not.

最好的推理方法是 List< ;?super Person> 没有确定的类型:它是一个 pattern ,它描述了允许作为参数的一系列类型.将 List< Person> 视为不是 List<的子类型?超级Person> ,但类型与此模式匹配. List< ;?上允许的操作?超级Person> 是任何匹配类型都允许的.

The best way to reason about it is that List<? super Person> is no definite type: it is a pattern describing a range of types that are allowed as an argument. Look at List<Person> as not a subtype of List<? super Person>, but a type that matches this pattern. The operations allowed on List<? super Person> are those that are allowed on any matching type.

这篇关于Java下限通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆