java cast from List<B> to List<A> where B extends A

爷,独闯天下 提交于 2019-12-01 21:02:38

问题


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.


回答1:


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



回答2:


Try

List<? extends A> = getList()



回答3:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!