类型推断:Java 7类型参数 [英] Type Inference: Java 7 Type Parameters
问题描述
Map< String,List< String>> myMap = new HashMap< String,List< String>>();
as
Map< String,List< String>> myMap = new HashMap<>();
我们对上述主题进行了长时间的讨论。我们中的一些人认为这是类型推理(如C#中的 var
关键字),并且类型将在运行时计算,其他人认为这只是一种更简单的方式来声明某些变量并且没有推断,因为在编译时上下文已知类型。
请提供说明。这种技术如何工作?
编辑:
官方Oracle文档没有提供关于该技术的精确文档。 http://docs.oracle.com/javase/tutorial/java/generics /genTypeInference.html
实际上,是类型推断。
菱形运算符(<>
)允许将赋值的右侧定义为一个具有与左手边相同类型参数的真实泛型实例,而不必再次键入这些参数(因为编译器从左手侧推断类型)。
它(菱形操作符)表示空角尖括号,它表示空角尖括号
更多信息:
$ b $用于类型推断 btoday we talked about advantages of Java 7 in our company. Since Java 7 there is the possibility to define following line
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
as
Map<String, List<String>> myMap = new HashMap<>();
We had a long discussion about the topic described above. Some of us had the opinion that this is type inference (like var
keyword in C#) and the type will be computed at runtime, others thought it's only a simpler way to declare some variable and there is no inference, because the type of is known by the context at compile time.
Please provide clarification. How dows the technique work?
EDIT: Official Oracle Documentation provides no precise documentation about that. http://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html
Actually, it is type inference.
The diamond operator (<>
), allows the right hand side of the assignment to be defined as a true generic instance with the same type parameters as the left hand side without having to type those parameters again (because the compiler infers the type(s) from the left hand side).
From the Angelika Langer's Generics FAQ:
It (the diamond operator) denotes the empty angle brackets that are used for type inference in new -expression.
More info:
这篇关于类型推断:Java 7类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!