如何将超类型列表转换为子类型列表? [英] How do you cast a List of supertypes to a List of subtypes?

查看:43
本文介绍了如何将超类型列表转换为子类型列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,假设您有两个类:

For example, lets say you have two classes:

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

我有一个返回 List 的方法,我想将该列表中的所有对象强制转换为 TestB 以便我最终得到一个 List.

I have a method that returns a List<TestA> and I would like to cast all the objects in that list to TestB so that I end up with a List<TestB>.

推荐答案

简单地转换为 List 几乎可以工作;但它不起作用,因为您不能将一个参数的泛型类型转换为另一个参数.但是,您可以通过中间通配符类型进行强制转换,并且它是允许的(因为您可以在通配符类型之间进行转换,只是带有未经检查的警告):

Simply casting to List<TestB> almost works; but it doesn't work because you can't cast a generic type of one parameter to another. However, you can cast through an intermediate wildcard type and it will be allowed (since you can cast to and from wildcard types, just with an unchecked warning):

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

这篇关于如何将超类型列表转换为子类型列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆