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
Release: 2024-12-08 19:28:11
Original
875 people have browsed it

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 {}
Copy after login

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;
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template