我看楼上有回答说 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 以及之后版本的