Java泛型语法

3

虽然以下语句可以编译通过,但我无法理解其含义:

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

说,第二个<Integer>,我们如何在方法名前面放置单个<Integer>?我怀疑它是泛型的声明,但无法在任何地方找到它。但我只知道像List<Integer>这样的定义,将<Integer>放在泛型类型后面。有人可以为我指出这个语法的教程或找到重复的问题吗(抱歉我在快速搜索中没有找到)?
非常感谢!

https://docs.oracle.com/javase/tutorial/extra/generics/methods.html - M A
同时请参阅 https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html。 - M A
这正是我在寻找的。谢谢!@manouti - zzy
1个回答

3

这被称为类型证明,并且在类型推断指南中被引用:

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);

实际上,类型见证让开发人员可以介入解决类型引擎无法正确推断数值类型的情况。在Java 7中,您会更常见和普遍地看到它的使用,而Java 8则改进了其类型推断能力。


1
谢谢!那绝对有帮助! - zzy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接