最有效的方式来强制List< SubClass>到List< BaseClass> [英] Most efficient way to cast List<SubClass> to List<BaseClass>
问题描述
我有一个 List< SubClass>
,我想把它视为 List< BaseClass>
。看起来不应该是一个问题,因为将 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< SubClass>
与列表< BaseClass>
可互换。不。保留对 List< SubClass>
的引用的代码将期望列表中的每个项目是 SubClass
。如果另一部分代码引用列表为 List< BaseClass>
,编译器将不会抱怨当 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>到List< BaseClass>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!