简体   繁体   中英

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 ". However in IntelliJ it's generating a warning that you don't usually get when casting to a more specific type. From the comments below it seems that this may simply be a bug in 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> to List<? extends Number> List<? extends Number> is a downcast and would normally require a check of the object's type at runtime. However, the runtime environment cannot check, if the type parameter is really a class that extents 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. The only thing about the cast that can be checked at runtime is therefore, if the Collection is a List .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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