2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

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

I have two classes lets say..

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

userimage

Just cast 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;
Answer is