java 返回 list 泛型_java中 Arrays.asList返回的泛型类型如何确定?

本文讨论了Java7及以上版本中,编译器如何利用目标类型推导来确定泛型方法调用的类型参数。通过举例解释了在没有明确指定泛型类型时,编译器如何根据返回值或参数类型推断正确的泛型类型。
摘要由CSDN通过智能技术生成

我看楼上有回答说 Java8 以下版本不可以编译你的代码,这是不对的。使用 Java7 也可以正确编译你的代码,因为 JDK7 对于泛型类型的推导不仅仅只有 “菱形推导”,还添加了部分目标类型推导的功能,可以参考 Oracle 的官方文档 Type Inference,看到 Target Types 这一节,我摘取部分:

The Java compiler takes advantage of target typing to infer the type parameters of a generic method invocation. The target type of an expression is the data type that the Java compiler expects depending on where the expression appears. Consider the method Collections.emptyList, which is declared as follows:

static List emptyList();

Consider the following assignment statement:

List listOne = Collections.emptyList();

This statement is expecting an instance of List; this data type is the target type. Because the method emptyList returns a value of type List, the compiler infers that the type argument T must be the value String. This works in both Java SE 7 and 8.

可以看到,对于 JDK7 以及之后版本的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值