Casting a List of Supertypes to a List of Subtypes
You may encounter a situation where you have a list of objects of a supertype and desire to cast them to a specific subtype. To illustrate, consider the following class hierarchy:
public class TestA {} public class TestB extends TestA {}
You may have a method returning a List
Solution
Directly casting to List
List<TestB> variable = (List<TestB>)(List<?>) collectionOfListA;
This cast is permitted because wildcard types can be both cast to and from, albeit with an unchecked warning. By utilizing the wildcard type as an intermediary, you can successfully cast your list of supertypes to your desired list of subtypes.
The above is the detailed content of How Can I Cast a List of Supertypes to a List of Subtypes in Java?. For more information, please follow other related articles on the PHP Chinese website!