编译器根据赋值的LHS上使用的具体类型推断出T的类型.
If the type parameter does not appear in the types of the method
arguments, then the compiler cannot infer the type arguments by
examining the types of the actual method arguments. If the type
parameter appears in the method’s return type, then the compiler takes
a look at the context in which the return value is used. If the
method call appears as the righthand side operand of an assignment,
then the compiler tries to infer the method’s type arguments from the
static type of the lefthand side operand of the assignment.
链接中的示例代码与您问题中的代码类似:
public final class Utilities {
...
public static HashSet create(int size) {
return new HashSet(size);
}
}
public final class Test
public static void main(String[] args) {
HashSet hi = Utilities.create(10); // T is inferred from LHS to be `Integer`
}
}