虽然以下语句可以编译通过,但我无法理解其含义:
List<Integer> l = Collections.<Integer>singletonList(5);
说,第二个
<Integer>
,我们如何在方法名前面放置单个<Integer>
?我怀疑它是泛型的声明,但无法在任何地方找到它。但我只知道像List<Integer>
这样的定义,将<Integer>
放在泛型类型后面。有人可以为我指出这个语法的教程或找到重复的问题吗(抱歉我在快速搜索中没有找到)?非常感谢!
虽然以下语句可以编译通过,但我无法理解其含义:
List<Integer> l = Collections.<Integer>singletonList(5);
<Integer>
,我们如何在方法名前面放置单个<Integer>
?我怀疑它是泛型的声明,但无法在任何地方找到它。但我只知道像List<Integer>
这样的定义,将<Integer>
放在泛型类型后面。有人可以为我指出这个语法的教程或找到重复的问题吗(抱歉我在快速搜索中没有找到)?这被称为类型证明,并且在类型推断指南中被引用:
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 methodaddBox
, you can specify the type parameter with a type witness as follows:
BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes);
实际上,类型见证让开发人员可以介入解决类型引擎无法正确推断数值类型的情况。在Java 7中,您会更常见和普遍地看到它的使用,而Java 8则改进了其类型推断能力。