Jeremy Logan Jeremy Logan - 9 months ago 57
Java Question

How do you cast a List of supertypes to a List of subtypes?

For example, lets say you have two classes:

public class TestA {}
public class TestB extends TestA{}

I have a method that returns a
and I would like to cast all the objects in that list to
so that I end up with a

Answer Source

Simply casting to List<TestB> almost works; but it doesn't work because you can't cast a generic type of one parameter to another. However, you can cast through an intermediate wildcard type and it will be allowed (since you can cast to and from wildcard types, just with an unchecked warning):

List<TestB> variable = (List<TestB>)(List<?>) collectionOfListA;