15.10

class Fruit{}

class Apple extends Fruit{}

Fruit[] fruit=new Apple[10];

fruit[0]=new Apple();//0k

fruit[0]=new Fruit()//exception runtime


List<Fruit> flist=new ArrayList<Apple>();//不能将一个Apple的容器赋值给一个Fruit容器,编译错误 incompatible error

这可以使用通配符来解决


Holder<? extends Fruit> fruit=Apple;ok

Fruit p=fruit.get();ok

Apple d=fruit.get(); ok


fruit.set(new Apple());  //Cannot call set()? Extends Fruit 编译器并不能了解这里需要Fruit的哪个子类型,不会接受任何类型的Fruit,编译器将直接拒绝对参数列表中涉及通配符的方法调用。


15.10.2 逆变

超类型通配符,List<? super Apple> apples 可以向其中添加对象

apples.add(new Apple());ok

apples.add(new Jonathan());ok

//apples.add(new Fruit());//Error

Apple是下界,向这样的List中添加Fruit是不安全的。

15.10.3 无界通配符

无界通配符<?> “任何事物”,使用无界通配符好像等价于使用原生类型


static<T> void wildSupertype(Holder<? super T> holder,T arg){

      holder.set(arg);

//T t=holder.get();//Error

//Incompatible types:found Object


Holder将持有任何类型的的组合,而Holder<?>将持有具有某种具体类型的同构集合,因此只是想其中传递Object。


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值