Reputation: 3181
I have been looking at OJCPA code snippets and I am confused why the compiler does not throw an error at the following code.
List l = new ArrayList();
l.add("a");
l.add("b");
l.add(1);
List<String> strList = new ArrayList<>();
strList = l; //#1 - Why does the assignment compile?
for(String s: strList) {
System.out.println(s); //#2 - It makes sense that it then throws a ClassCastException
}
I thought that the compiler would see List l as a raw type and because generics are invariant it would produce a compiler error, as it is not of type List< String >.
Thanks for you help.
Upvotes: 8
Views: 88
Reputation: 393781
It is allowed for backwards compatibility.
Suppose that you are calling a legacy method that returns a List
of String
s, but it was written before generics were added to Java, so it returns a raw List
.
You'd want this line to pass compilation :
List<String> strList = someOldMethodThatReturnsRawList();
Otherwise you'll have to keep using the raw List
type in your new code in order to call that method.
Upvotes: 7