Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: cast collection type to subtype [duplicate]

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.

like image 942
Landon Kuhn Avatar asked Oct 30 '09 16:10

Landon Kuhn


2 Answers

You can cast through the untyped List interface:

List<A> a = new ArrayList<A>(); List<B> b = (List)a; 
like image 141
jarnbjo Avatar answered Sep 21 '22 13:09

jarnbjo


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.

like image 35
Romain Avatar answered Sep 19 '22 13:09

Romain