Reputation:
How we can use Java 7 Type inference for generic instance creation feature ? What all benefits to use this new style?
Upvotes: 0
Views: 2814
Reputation: 3649
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.
Upvotes: 2
Reputation: 94499
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>();
Upvotes: 5
Reputation: 262834
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.
Upvotes: 1