Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does new LinkedList<>() differ from new LinkedList()

Tags:

java

generics

I just stumbled upon the compiler treating these two terms differently. when I type:

LinkedList<String> list = new LinkedList();

I get a compiler warning about a raw type. however:

LinkedList<String> list = new LinkedList<>();

removes the warning. It seems to me as though the two statements mean essentially the same thing (i.e. create a new LinkedList with no specified object type). Why then does the complier all ow the empty generics? What is the difference here?

like image 402
ewok Avatar asked Dec 27 '22 21:12

ewok


2 Answers

The statements do not mean the same thing at all.

The first statement tries to fit an untyped LinkedList into a declared generic LinkedList<String> and appropriately throws a warning.

The second statement, valid in Java 1.7 onward, uses type inference to guess the type parameter by using the declaring type's type parameter. In addition, sometimes this can be used in method calls. It doesn't always work, however.

See this page for more info.

like image 63
Platinum Azure Avatar answered Dec 29 '22 10:12

Platinum Azure


It's the diamond operator in Java 7, that helps you save writing the type again. In Java 7 this is equivalent to the same generic type argument that is used on the left side of the declaration. So the initialization is type safe and no warning is issued.

like image 40
Arne Avatar answered Dec 29 '22 09:12

Arne