In Java, you can encounter scenarios where you have a list of supertype objects and desire to obtain a list of their subtype counterpart. This raises the question: how do you cast a List
For instance, consider the following two classes:
public class TestA {} public class TestB extends TestA {}
A method returns a List
The solution involves casting the list through an intermediate wildcard type. Direct casting to List
List<TestB> variable = (List<TestB>)(List<?>) collectionOfListA;
This approach leverages the ability to cast to and from wildcard types. The unchecked warning is displayed because the compiler cannot guarantee the type safety of the cast.
The above is the detailed content of How to Cast a List to a List in Java?. For more information, please follow other related articles on the PHP Chinese website!