Home >Java >javaTutorial >How Can I Safely Cast a List of Supertypes to a List of Subtypes in Java?

How Can I Safely Cast a List of Supertypes to a List of Subtypes in Java?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-08 19:28:11885browse

How Can I Safely Cast a List of Supertypes to a List of Subtypes in Java?

Casting List of Supertypes to List of Subtypes

Consider the following scenario involving two classes:

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

You have a method that returns a List and want to convert it to a List without losing type safety.

Casting Approach

Casting to List directly doesn't work due to type erasure. However, there's a workaround using an intermediate wildcard type:

List<TestB> variable = (List<TestB>)(List<?>) collectionOfListA;

This approach is allowed because you can cast to and from wildcard types, albeit with an unchecked warning. The wildcard type acts as an intermediate step, allowing you to cast the list of supertype elements to a list of subtype elements.

The above is the detailed content of How Can I Safely 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn