Java: cast collection type to subtype

43,542

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 that C<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.

Share:
43,542
Landon Kuhn
Author by

Landon Kuhn

Updated on October 14, 2020

Comments

  • Landon Kuhn
    Landon Kuhn over 3 years

    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.