java tbase_Java 泛型中<? extends Base> 和 <T extends Base>区别及示例代码

使用出现异常代码:import java.util.*;

public class Example {

static void doesntCompile(Map> map) {}

static void compiles(Map> map) {}

static void function(List extends Number> outer)

{

doesntCompile(new HashMap>());

compiles(new HashMap>());

}

}

doesntCompile()方法编译错误如下:Example.java:9: error: incompatible types: HashMap> cannot be converted to Map>

doesntCompile(new HashMap>());

通过使用以下签名定义方法:static void compiles(Map> map) {}

如下代码调用:compiles(new HashMap>());

§8.1.2中介绍内容:泛型类声明定义了一组参数化类型(§4.5),每个类型参数都可以调用类型参数部分。所有这些参数化类型在运行时共享同一个类。

换句话说,将类型T与输入类型进行匹配并进行分配Integer。签名将有效地变为static void compiles(Map> map)。

关于doesntCompile方法,jls定义了子类型化规则(第4.5.1节,):

? extends T <= ? extends S if T <: s>

? extends T <= ?

? super T <= ? super S if S <: t>

? super T <= ?

? super T <= ? extends Object

T <= T

T <= ? extends TT <= ? super T

如此说明,? extends Number确实包含Integer甚至List extends Number>包含List,但Map> 并非如此Map>。您仍然可以?通过声明期望使用以下子类型来使带有通配符的版本起作用List extends Number>:public class Example {

// 可以正常编译

static void doesntCompile(Map> map) {}

static void compiles(Map> map) {}

public static void main(String[] args) {

doesntCompile(new HashMap>());

compiles(new HashMap>());

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值