转换 List<SubClass> 的最有效方法列出<BaseClass> [英] Most efficient way to cast List<SubClass> to List<BaseClass>
问题描述
我有一个 List
,我想将其视为 List
.似乎这应该不是问题,因为将 SubClass
转换为 BaseClass
很容易,但我的编译器抱怨无法进行转换.
I have a List<SubClass>
that I want to treat as a List<BaseClass>
. It seems like it shouldn't be a problem since casting a SubClass
to a BaseClass
is a snap, but my compiler complains that the cast is impossible.
那么,获得对与 List
相同对象的引用的最佳方法是什么?
So, what's the best way to get a reference to the same objects as a List<BaseClass>
?
现在我只是制作一个新列表并复制旧列表:
Right now I'm just making a new list and copying the old list:
List<BaseClass> convertedList = new ArrayList<BaseClass>(listOfSubClass)
但据我所知,这必须创建一个全新的列表.如果可能,我想参考原始列表!
But as I understand it that has to create an entirely new list. I'd like a reference to the original list, if possible!
推荐答案
这种赋值的语法使用通配符:
The syntax for this sort of assignment uses a wildcard:
List<SubClass> subs = ...;
List<? extends BaseClass> bases = subs;
认识到List
与List
不能互换很重要.保留对List
的引用的代码将期望列表中的每个项目都是一个SubClass
.如果代码的另一部分将列表称为 List
,则在插入 BaseClass
或 AnotherSubClass
时,编译器不会报错.但这将导致第一段代码出现 ClassCastException
,它假定列表中的所有内容都是 SubClass
.
It's important to realize that a List<SubClass>
is not interchangeable with a List<BaseClass>
. Code that retains a reference to the List<SubClass>
will expect every item in the list to be a SubClass
. If another part of code referred to the list as a List<BaseClass>
, the compiler will not complain when a BaseClass
or AnotherSubClass
is inserted. But this will cause a ClassCastException
for the first piece of code, which assumes that everything in the list is a SubClass
.
泛型集合的行为与 Java 中的数组不同.数组是协变的;也就是说,允许这样做:
Generic collections do not behave the same as arrays in Java. Arrays are covariant; that is, it is allowed to do this:
SubClass[] subs = ...;
BaseClass[] bases = subs;
这是允许的,因为数组知道"其元素的类型.如果有人试图在数组中存储不是 SubClass
实例的东西(通过 bases
引用),将抛出运行时异常.
This is allowed, because the array "knows" the type of its elements. If someone attempts to store something that isn't an instance of SubClass
in the array (via the bases
reference), a runtime exception will be thrown.
泛型集合不知道"它们的组件类型;此信息在编译时被擦除".因此,当发生无效存储时,它们无法引发运行时异常.相反,当从集合中读取值时,将在代码中某个遥远的、难以关联的点处引发 ClassCastException
.如果您注意编译器关于类型安全的警告,您将在运行时避免这些类型错误.
Generic collections do not "know" their component type; this information is "erased" at compile time. Therefore, they can't raise a runtime exception when an invalid store occurs. Instead, a ClassCastException
will be raised at some far distant, hard-to-associate point in code when a value is read from the collection. If you heed compiler warnings about type safety, you will avoid these type errors at runtime.
这篇关于转换 List<SubClass> 的最有效方法列出<BaseClass>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!