Java raw type declaration

Viewed 785

Well, there were many question on this site regarding raw types and generics in Java. Even questions regarding why does the next line of code comes up with a warning:

List<String> list = new ArrayList();

And answered many times, since ArrayList() is of raw type, therefore the compiler raises a warning since now list is not "type safe", and the option to write this line of code is solely for backward compatibility.

What I don't understand, and didn't find questions about it, is why? Since the compiler compiles the Java code by "looking" only on the static references, how come there is a difference in compilation time for writing new ArrayList(); instead of new ArrayList<>();.

For example, writing this code:

List<String> list = new ArrayList(); // 1
list.add("A string"); // 2
list.add(new Object()); // 3

results in a compilation warning in line 1, no compilation problem in line 2, but a compilation error in line 3 - of type safety.

Therefore - adding a generic reference to the first line (new ArrayList<>();), results only in the removal of the compiler warning.

I understand it's a bad habit to use raw types, but my question is really what is the difference (except for the compilation warning) in writing the right hand side as a raw type.

Thanks!

2 Answers
Related