Java:从 List<B> 进行转换列出<A>B什么时候实现A? [英] Java: Casting from List&lt;B&gt; to List&lt;A&gt; when B implements A?

查看:29
本文介绍了Java:从 List<B> 进行转换列出<A>B什么时候实现A?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following class & interface defined:

public interface A {
}

public class B implements A {
}

我有一个 B 对象的 List,我需要将其转换为 A 对象的 List:

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;

上面的最后一行导致编译错误无法从 List 转换为 List".我尝试使用以下方法解决此问题:

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());

不幸的是,这会引发 ClassCastException.有谁知道我该如何解决这个问题?

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.无论如何它都会指向相同的引用.

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

这篇关于Java:从 List<B> 进行转换列出<A>B什么时候实现A?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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