Java:将集合类型转换为子类型 [英] Java: cast collection type to subtype
本文介绍了Java:将集合类型转换为子类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设类 B
扩展类 A
。我有一个列表< A>
我恰好知道只有包含 B
。是否有一种方法可以将 List
转换为列表< B>
?
Suppose class B
extends class A
. I have a List<A>
that I happen to know only contains instances of B
. Is there a way I can cast the List<A>
to a List<B>
?
看来我唯一的选择是迭代集合,在时间转换一个元素,创建一个新的集合。
It seems my only option is to iterate over the collection, casting one element at time, creating a new collection. This seems like an utter waste of resources given type erasure makes this completely unnecessary at run-time.
推荐答案
你可以通过未分类的列表界面:
You can cast through the untyped List interface:
List<A> a = new ArrayList<A>();
List<B> b = (List)a;
这篇关于Java:将集合类型转换为子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文