java Cast from List< B>到列表< A>其中B延伸A [英] java cast from List<B> to List<A> where B extends A

查看:405
本文介绍了java Cast from List< B>到列表< A>其中B延伸A的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是可能吗?

 接口B扩展A {} 
public List< B> ; getList();
List< A> = getList(); // Type mismatch:can not convert from List< B>到列表< A>

我认为我正在寻找的主题是协变类型为此处

p>这是一个直观的例子,如何这可以使事情变得可怕的错误:

 接口B扩展A {} 
List< B> blist = new List< B>();
List< A> alist = blist
alist.add(new A()); //应该是好的,对吧?
B b = b1ist.get(0); // fail:即使blist是List< B> ;,它现在有一个A in


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

这篇关于java Cast from List&lt; B&gt;到列表&lt; A&gt;其中B延伸A的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆