Reputation: 11120
Recently I encountered the code like this: List<Person> somevar = new ArrayList<>();
I don't understand how the variable declared with specialized generic type List<Person>
can be initialized with a non-generic type constructor ArrayList<>();
The latter code obviously works fine, but why? and how?
Thank you
Upvotes: 2
Views: 76
Reputation: 5424
It's called Diamond Operator
, and it's just a syntactic sugar to write less code. It's equivalent to:
List<Person> somevar = new ArrayList<Person>();
It's available since Java/JDK 7
.
Upvotes: 3
Reputation: 5604
It is called "The Diamond Operator". The reason you don't have to add a type parameter, is because it is inferred by the left-side variable you are assigning it too.
It is similar as with generic methods. Type inference was already working on these before Java 7:
This seems to be a good article about it: http://www.javaworld.com/article/2074080/core-java/jdk-7--the-diamond-operator.html
Upvotes: 2
Reputation: 2848
new ArrayList<>;
is not a valid syntax.
A valid syntax would be new ArrayList<>();
which is referred to as the "diamond notation". It is not non-generic: the compiler will deduce the type from the context.
non-Generic would be new ArrayList();
Upvotes: 0