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

风格不统一 提交于 2019-12-01 18:47:42

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)

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