Specifying the type of collection items when instantiating

Is there a difference between the following ads:

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

and

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

In both cases, in any case, the list will contain only elements of type String.

+3
source share
1 answer

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

* Basically, the removal of redundant information and code noise reduction was introduced. So now you have:

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

against

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

The first one is much easier on the eyes.

+5
source

All Articles