类型推断:Java 7类型参数 [英] Type Inference: Java 7 Type Parameters

查看:132
本文介绍了类型推断:Java 7类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我们谈到了我们公司的Java 7的优势。从Java 7开始,可以定义以下行:

  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


它(菱形操作符)表示空角尖括号,它表示空角尖括号

更多信息:

$ b $用于类型推断

b

today 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆