简体   繁体   English

通用实例创建的Java7类型推断?

[英]Java7 Type inference for generic instance creation?

How we can use Java 7 Type inference for generic instance creation feature ? 我们如何将Java 7 类型推断用于通用实例创建功能? What all benefits to use this new style? 使用这种新样式有什么好处?

This is also known as the diamond operator. 这也称为菱形运算符。 It saves you from having to write the generic type arguments on the instantiation of a generic type. 它使您不必在泛型类型的实例化上编写泛型类型参数。 The type arguments of the instantiated generic type are inferred from the type arguments present on the declaration. 实例化泛型类型的类型参数是从声明上存在的类型参数推断出来的。

ArrayList<String> list = new ArrayList<>();

Instead of: 代替:

ArrayList<String> list = new ArrayList<String>();

No. The diamond syntax is merely a shorthand in coding/typing. 不。菱形语法只是编码/键入中的简写。 These two are the same 这两个是一样的

List<String> a = new ArrayList<String>();  
List<String> a = new ArrayList<>();  

They are treated the same for the compiling process, hints to the compiler. 在编译过程中,它们被视为相同,这提示编译器。 Even before type erasure, they are treated the same. 即使在类型擦除之前,也将它们视为相同。 It's literally just a convenience for you. 从字面上看,这只是为您提供便利。

It's just less typing. 只是打字少了。

From the docs : 文档

For example, consider the following variable declaration: 例如,考虑以下变量声明:

Map<String, List<String>> myMap = new HashMap<String, List<String>>();

In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>): 在Java SE 7中,可以用一组空的类型参数(<>)代替构造函数的参数化类型:

Map<String, List<String>> myMap = new HashMap<>();

Unfortunately, you still have to type the diamond . 不幸的是, 您仍然必须键入菱形

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM