Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying collection elements type while instance creation

Is there any difference between the following declarations -

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

and

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

In both cases anyhow , list will have elements of type String only.

like image 238
Vivek Vermani Avatar asked Mar 03 '26 04:03

Vivek Vermani


1 Answers

There is no difference. However, the first one is legal in Java <= 7 whereas the second one is legal only in Java 7 and was introduced as a short-hand notation*. The compiler will infer the generic type from the declaration.

*It was basically introduced to remove redundant information and reduce code-noise. So you now have:

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

versus:

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

The first one is a lot easier on the eyes.

like image 118
Vivin Paliath Avatar answered Mar 05 '26 18:03

Vivin Paliath