简体   繁体   English

未经检查的涉及通配符类型的演员表

[英]Unchecked cast involving wildcard types

Can somebody explain why this is an unchecked cast 有人可以解释为什么这是未经检查的演员吗

static void foo(Collection<? extends Number> collection) {
    List<? extends Number> list = (List<? extends Number>) collection;
}

but this isn't? 但这不是吗?

static void bar(List<? extends Number> list) {
    Collection<? extends Number> collection = (Collection<? extends Number>) list;
}

I think it's got something to do with captures, but I'd like a clear explanation. 我认为这与捕获有关,但是我想要一个清晰的解释。

Edit 编辑

I realise that this is a badly worded question, and that the correct answer is "because List extends Collection ". 我意识到这是一个措辞不佳的问题,正确的答案是“因为List扩展了Collection ”。 However in IntelliJ it's generating a warning that you don't usually get when casting to a more specific type. 但是,在IntelliJ中,它会生成警告,强制转换为更特定的类型时通常不会得到警告。 From the comments below it seems that this may simply be a bug in IntelliJ. 从下面的评论看来,这可能只是IntelliJ中的错误。 The exact warning is in the comments below (for some reason I can't reproduce it here). 确切的警告在下面的注释中(由于某些原因,我在这里无法重现)。 I don't get a warning on any of the following 我没有收到以下任何警告

static void foo(Collection<Number> collection) {
    List<Number> list = (List<Number>) collection;
}

static <T> void foo(Collection<T> collection) {
    List<T> list = (List<T>) collection;
}

static void foo(Collection<?> collection) {
    List<?> list = (List<?>) collection;
}

Because the cast from List<? extends Number> 因为从List<? extends Number> List<? extends Number> to List<? extends Number> List<? extends Number>List<? extends Number> List<? extends Number> is a downcast and would normally require a check of the object's type at runtime. List<? extends Number>是一个下垂的选项,通常需要在运行时检查对象的类型。 However, the runtime environment cannot check, if the type parameter is really a class that extents Number . 但是,运行时环境无法检查type参数是否确实是扩展Number的类。 That information isn't available at runtime, Java Generics ("type parameters") only exist in the static Java type system, they don't affect the compiled code. 该信息在运行时不可用,Java泛型(“类型参数”)仅存在于静态Java类型系统中,它们不会影响已编译的代码。 The only thing about the cast that can be checked at runtime is therefore, if the Collection is a List . 因此,关于Collection的唯一可以在运行时检查的是,如果CollectionList

The other case is a simple upcast, where no runtime information is necessary. 另一种情况是简单的转换,不需要任何运行时信息。 You can check at compile time, that this cast will always work. 您可以在编译时检查该强制转换将始终有效。 The lack of information about the type parameter at runtime is therefore irrelevant. 因此,在运行时缺少有关类型参数的信息是无关紧要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM