Java: cast collection type to subtype

Landon Kuhn picture Landon Kuhn · Oct 30, 2009 · Viewed 41.4k times · Source

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.

Answer

jarnbjo picture jarnbjo · Oct 30, 2009

You can cast through the untyped List interface:

List<A> a = new ArrayList<A>();
List<B> b = (List)a;