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

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

DDD
Release: 2024-12-27 17:15:12
Original
134 people have browsed it

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

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

You may have a method returning a List, and you wish to cast each item in the list to TestB, resulting in a List.

Solution

Directly casting to List will not succeed because it violates Java's generic type safety rules. However, you can employ a trick by casting through an intermediate wildcard type:

List<TestB> variable = (List<TestB>)(List<?>) collectionOfListA;
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template