java 从 List 转换到列表其中 B 延伸 A
这可能吗?如果不是,为什么这在 Java 中不可能呢?
interface B extends A {}
public List<B> getList();
List<A> = getList(); // Type mismatch: cannot convert from List<B> to List<A>
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
下面是一个直观的例子,说明了这会如何导致事情变得严重错误:
Here is an intuitive example of how this can make things go horribly wrong:
尝试
Try
你不能这样做的原因是A和B不一样,你已经指定getList返回B的List(不是超类或子类)
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)