从List< Optional>投射是否安全?列出<可选<?>> ;? [英] Is it safe to cast from List<Optional> to List<Optional<?>>?
问题描述
如果您在Java中有一个原始类型,则可以使用无限制的通配符将其安全地分配/转换为相同的类型。例如,一个 List
可以安全地转换为 List<?>
,这会消除它的原始性质,并允许你以安全的方式使用它(类型检查)。
List 本身用原始类型参数化,如 List< Optional>
列表具有无限通配符的相同类型参数,如 List< Optional<>>
。
您仍然可以通过完全放弃原始 List
并重新备份(隐式地通过分配):
列表< Optional> rawOptionalList = null;
列表<可选<?>> wildcardOptionalList =(List)rawOptionalList;
当然,这会触发有关未检查转换的警告(从 List
到 List< Optional<>>
)。
在我看来,这种转换是安全的:不是 List< Optional<>>
与列表<可选>
一样安全,就像将原始可选
转换为是安全的吗?
sup> ...但是你永远无法添加任何东西到这个列表中,因为没有任何东西能够匹配添加的?
?)
方法。这是你为了安全而付出的代价。
是的,这是安全的。通用检查仅在编译时。
If you have a raw type in Java, you can safely assign/cast this to the same type with an unbounded wildcard. For example a List
can be safely cast to a List<?>
, which removes its raw nature and allows you to use it in a safe (type-checked) manner1.
On the other hand, Java doesn't let you cast from a List
itself parameterized with a raw type, like List<Optional>
to a list of the same type parameter with an unbounded wildcard, like List<Optional<?>>
.
You can still do it by dropping all the way down a raw List
and back up again (implicitly via the assignment):
List<Optional> rawOptionalList = null;
List<Optional<?>> wildcardOptionalList = (List)rawOptionalList;
Of course, this triggers warning about unchecked conversion (from List
to List<Optional<?>>
).
It seems to me though that this conversion is guaranteed safe: isn't List<Optional<?>>
just as safe as List<Optional>
in the same way that casting a raw Optional
to an Optional<?>
is safe?
1 ... but you'll never be able to add anything to this list, since nothing will match the capture of ?
for the add(?)
method. That's the price you pay for safety.
解决方案 Yes, it's safe. The generic check is just at compile time.
这篇关于从List< Optional>投射是否安全?列出<可选<?>> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!