Home > Java > javaTutorial > How to Cast a List to a List in Java?

How to Cast a List to a List in Java?

Patricia Arquette
Release: 2024-12-06 19:10:16
Original
1020 people have browsed it

How to Cast a List to a List in Java?

Casting a List of Supertypes to a List of Subtypes

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 to a List?

For instance, consider the following two classes:

public class TestA {}
public class TestB extends TestA {}
Copy after login

A method returns a List, and you wish to transform all the elements within it to TestB objects, resulting in a List.

The solution involves casting the list through an intermediate wildcard type. Direct casting to List is not feasible due to the inability to cast generic types of different parameters. However, casting to a wildcard type is allowed, with an unchecked warning issued:

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

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!

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