Java:将集合类型转换为子类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1651030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: cast collection type to subtype
提问by Landon Kuhn
Suppose class B
extends class A
. I have a List<A>
that I happen to know onlycontains instances of B
. Is there a way I can cast the List<A>
to a List<B>
?
假设 classB
扩展 class A
。我有一个List<A>
我碰巧知道只包含B
. 有没有办法可以将 the 转换List<A>
为 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.
似乎我唯一的选择是迭代集合,一次投射一个元素,创建一个新集合。鉴于类型擦除在运行时完全没有必要,这似乎完全浪费了资源。
采纳答案by jarnbjo
You can cast through the untyped List interface:
您可以通过无类型的 List 接口进行转换:
List<A> a = new ArrayList<A>();
List<B> b = (List)a;
回答by Joachim Sauer
List<A>
is nota subtype of List<B>
!
List<A>
是不是一个亚型List<B>
!
The JLS even mentions that explicitly:
Subtyping does not extend through generic types:
T <: U
does not imply thatC<T> <: C<U>
.
子类型
T <: U
不通过泛型类型扩展:并不意味着C<T> <: C<U>
.
回答by Romain
You can try this :
你可以试试这个:
List<A> a = new ArrayList<A>();
List<B> b = (List<B>) (List<?>) a;
It is based on the answer of jarnbjo, but on don't use raw lists.
它基于 jarnbjo 的答案,但不要使用原始列表。
回答by zakmck
A way to retain some type safety with minimum impact on performance is to use a wrapper. This example is about Collection, the List case would be very similar and maybe one day I'll write that too. If someone else comes before me, please let's share the code.
一种在对性能影响最小的情况下保留某种类型安全性的方法是使用包装器。这个例子是关于 Collection 的,List 的情况非常相似,也许有一天我也会写这个。如果有人在我之前,请让我们分享代码。