First, you may already know, but for others: Using raw types is bad. We shouldn’t. Meaning we don’t need to know the answer to your question.
Curiosity doesn’t quite kill this cat, though, so for its sake: Once you use a raw type, everything in the expression goes raw. So when you pass a raw HashMap
to doSometing()
, it returns a raw List
, not the List<B>
that it’s declared to return. And Java accepts that you assign a raw List
to a List<A>
. With a warning. But you’re expected to know best, if you say that the list can be regarded as a List<A>
, so be it.
In you last code line you haven’t got any raw types, so generics work the way they are supposed to. doSomething()
returns a List<B>
. And you cannot assign a List<B>
to a List<A>
. Why? Because a List<A>
would allow you to insert something into the list that implements A
but is not a B
. We cannot allow that to happen for a List<B>
.
Link: What is PECS (Producer Extends Consumer Super)? about why you can’t assign a List<B>
to a List<A>
and what to do instead.