Jeremy Logan Jeremy Logan - 19 days ago 7
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
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

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;