Java:从列表< B>到列表< A>当B实现A? [英] Java: Casting from List<B> to List<A> when B implements A?

查看:117
本文介绍了Java:从列表< B>到列表< A>当B实现A?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程&接口定义:

I have the following class & interface defined:

public interface A {
}

public class B implements A {
}

我有一个列表 > B 对象,我需要转换为 $ c> objects:

I have a List of B objects that I need to cast to a List of A objects:

List<B> listB = new List<B>();
listB.add(new B());  // dummy data
listB.add(new B());  // dummy data
listB.add(new B()); // dummy data

List<A> listA = (List<A>) listB;

上面的最后一行导致编译错误无法从列表< B>转换到列表< A& 。我试图解决这个与下面的代替:

The last line above results in compile error "Cannot cast from List<B> to List<A>". I attempted to work around this with this following instead:

List<A> listA = Arrays.asList((A[]) listB.toArray());


$ b <有人知道我该如何解决这个问题吗?

Unfortunately, that throws a ClassCastException. Does anyone know how I can resolve this?

推荐答案

你不能这样。创建一个新的:

You cannot cast it like that. Create a new one:

List<A> listA = new ArrayList<A>(listB);

构造函数需要 Collection< ;?扩展A> 。它将指向相同的引用。

The constructor takes Collection<? extends A>. It will point to the same references anyway.

这篇关于Java:从列表&lt; B&gt;到列表&lt; A&gt;当B实现A?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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