简体   繁体   English

java从List转换<B>为List <A>,其中B扩展为A.</a>

[英]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.

相关问题 <A><B>当B扩展A时,</a>从列表转换<A>为列表</a> - Cast from List<A> to List<B> when B extends A 如果B扩展了A,则不能将List强制转换<A>为List <B>(很有意义),但是为什么一个可以将List强制转换</a> <? extends A> <A><B>列出<B>?</a> - If B extends A, one cannot cast List<A> to List<B> (makes sense), but then why can one cast List<? extends A> to List<B>? 新列表<A & ? extends B>();</a> - new List<A & ? extends B>(); 带通配符的泛型(地图 <? extends A, List<? extends B> &gt;) - Generics with Wildcards (Map<? extends A, List<? extends B>>) Java:<B><A>当 B 实现 A 时</a>从列表转换<B>到列表<A>?</a> - Java: Casting from List<B> to List<A> when B implements A? 添加(列表<!--? extends Z--> ) 其中 Z 是一个接口。 Class B 扩展 A 实现 Z 为什么我们不能用 List 调用 add()<a></a> - add (List<? extends Z>) where Z is an interface . Class B extends A implements Z why cant we call add() with a List<A> 展平列表<a>,其中每个 A 包含每个不同 B的列表</a> - Flatten List<A> where each A contains a List<B> for every distinct B Java Generics创建扩展A类并实现接口B的对象列表 - Java Generics create list of objects which extends class A and implements interface B Java推土机-要列出的元素A - Java Dozer - Element A to List<B> 在列表上使用addAll() <? extends E> a和b不起作用 - Using addAll() on List<? extends E> a and b doesn't work
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM