Java: cast collection type to subtype
Solution 1
You can cast through the untyped List interface:
List<A> a = new ArrayList<A>();
List<B> b = (List)a;
Solution 2
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.
Solution 3
List<A>
is not a subtype of List<B>
!
The JLS even mentions that explicitly:
Subtyping does not extend through generic types:
T <: U
does not imply thatC<T> <: C<U>
.
Solution 4
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.
Landon Kuhn
Updated on October 14, 2020Comments
-
Landon Kuhn over 3 years
Suppose class
B
extends classA
. I have aList<A>
that I happen to know only contains instances ofB
. Is there a way I can cast theList<A>
to aList<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.