java泛型 <>,Java泛型<?扩展a>v.s<a>vs<?超级A>[副本]

这可能是一个非常愚蠢的问题,但是我不明白为什么编译器会抱怨和编译。

我有两个非常简单的课程:

class A {

}

class B extends A {

}

现在代码:

//block1

List 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?

我知道它为什么起作用。

街区2,我有

extends 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)

3号街区,我有

super A>

,据我所知,列表将接受类型为

或超类型

,

是一个

亚型

属于

为什么

add(new B())

编译?

我想我可能误解了

super

extends

关键词,我做了一些谷歌,但我的怀疑仍然存在。

The term List 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值