[英]java cast from List<B> to List<A> where B extends A
is this possible? 这可能吗? if not, why isn't this possible in Java?
如果没有,为什么这不可能在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
尝试
List<? extends A> = getList()
你不能这样做的原因是A和B不一样,你指定getList返回一个B的List(不是超类或子类)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.