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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With