Giorgi Tsiklauri
Giorgi Tsiklauri

Reputation: 11120

Generic Type with non-Generic Implementation

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

Answers (3)

ka4eli
ka4eli

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

ByteWelder
ByteWelder

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

dotvav
dotvav

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

Related Questions