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

Jeremy Logan picture Jeremy Logan · Jun 1, 2009 · Viewed 272.6k times · Source

For example, lets say you have two classes:

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

I have a method that returns a List<TestA> and I would like to cast all the objects in that list to TestB so that I end up with a List<TestB>.

Answer

newacct picture newacct · Jun 1, 2009

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;