List<String> list = new LinkedList<String>();
does the following:
- Declare a variable called
list
with type List<String>
- Call the constructor of
LinkedList
with the type parameter String
- Sets the value of
list
to the result of step 2.
Since a List<String>
is obviously not going to be given a new LinkedList<Elephant>();
, it is OK to remove the type parameter from the second part, giving: List<String> list = new LinkedList<>();
. This is called "Type Inference". Java can only do this when it can calculate at compile-time what the omitted type would be.
If you use List list = new LinkedList<String>();
, you do exactly the same thing as above, except your new variable list
does not contain type information. This can be dangerous, as it prevents the compiler from warning/stopping you when you do something that would cause a type error.
For example:
List<String> list = new LinkedList<>();
list.add("hello"); // works fine
list.add(123); // compile-time error
I have been saved from putting an int
into a list of String
s. However, if using a regular List
:
List list = new LinkedList<String>();
list.add("hello"); // stil works
list.add(123); // also works
The issue with this comes from when you then retrieve items from the list:
List list = new LinkedList<String>();
list.add(123); // allowed
Object obj = list.get(0); // is obj a String? is it an int?
This breaks type safety, which is arguably a strong reason for using Java in the first place.