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;