is this possible? if not, why isn't this possible in Java?
interface B extends A {}
public List<B> getList();
List<A> = getList(); // Type mismatch: cannot convert from List<B> to List<A>
I think the topic I'm looking for is "covariant types" as here and here, but its murky and it doesn't solve my problem.
Here is an intuitive example of how this can make things go horribly wrong:
interface B extends A {}
List<B> blist=new List<B>();
List<A> alist=blist;
alist.add(new A()); //should be ok, right?
B b = blist.get(0); //fail: even though blist is a List<B>, it now has an A in it
Try
List<? extends A> = getList()
The reason you can't do this is that A and B are not the same, you have specified getList returns a List of B (not a super class or a sub class)
来源:https://stackoverflow.com/questions/7690684/java-cast-from-listb-to-lista-where-b-extends-a