简体   繁体   中英

Java7 Type inference for generic instance creation?

How we can use Java 7 Type inference for generic instance creation feature ? 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 (<>):

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

Unfortunately, you still have to type the diamond .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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