Java 泛型语法

Java generics grammar

虽然确实可以编译,但我无法理解以下语句:

List<Integer> l = Collections.<Integer>singletonList(5);

你说,第二个<Integer>,怎么在方法名前加一个<Integer>呢?我怀疑这是泛型声明,但无法在任何地方找到它。但是我只知道List<Integer>这样的定义,把<Integer>放在一个泛型类型后面。谁能给我指出这个语法的教程或找到重复的问题(抱歉,我在快速搜索期间没有找到)?

非常感谢!

这称为 类型见证,并在 Type Inference trail:

中引用

The generic method addBox defines one type parameter named U. Generally, a Java compiler can infer the type parameters of a generic method call. Consequently, in most cases, you do not have to specify them. For example, to invoke the generic method addBox, you can specify the type parameter with a type witness as follows:

BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes);

有效地,类型见证让开发人员介入解决类型引擎无法正确推断值将导致什么类型的情况。您会在 [=21 中看到它更常见和普遍的用法=] 7,而 Java 8 改进了它的类型推断能力。