fudy
fudy

Reputation: 1629

Two ways to new ArrayList in java

Generally, I can new an ArrayList in this way(if element is String):

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

However, I find a new way to do it:

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

It seems I can save much code by the second way if the element in the list is complex type.

Any difference between those?

Upvotes: 0

Views: 70

Answers (3)

Suresh Atta
Suresh Atta

Reputation: 122026

Type inference was added in JDK 1.7, the second style.

It seems I can save much code by the second way if the element in the list is complex type.

You it automacially infers if you are using 1.7 or +, which means the ArrayList gets the type of It's declared List.

Called as Diamond operator and purpose of the diamond operator is to simplify instantiation of generic classes.

Upvotes: 3

Kayaman
Kayaman

Reputation: 73578

Yes, the second version isn't supported before Java (compiler) version 1.7.

Therefore if you want your source code to be compilable with JDK 1.6, it can't use the new syntax.

Upvotes: 2

Amila
Amila

Reputation: 5213

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

This is an example of Type Inference for Generic Instance Creation (<> is informally called "diamond operator") which was introduced in Java 7.

You're encouraged to use it on Java 7 or Later for brevity of code.

Upvotes: 2

Related Questions