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

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

问题描述

例如,假设你有两个类:

For example, lets say you have two classes:

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



我有一个方法返回 List< TestA& / code>,我想把该列表中的所有对象转换为 TestB ,以便我结束一个 List< TestB& $

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< TestB> 几乎工作;但它不工作,因为你不能将一个类型的一个参数转换到另一个。但是,您可以通过中间通配符类型强制转换,并允许使用(因为您可以对通配符类型进行转换,只需使用未选中的警告):

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天全站免登陆