简体   繁体   中英

Java generics with wildcards and static wrappers

Excuse me about so generic question title, but was not sure how to call my question properly.

See the default types of result of Collections.singleton calls:

Set<Number> numberSingleton = 
    Collections.singleton((Number) null);

Set<Collection> rawCollectionSingleton = 
    Collections.singleton((Collection) null);

Set<Collection<String>> stringCollectionSingleton = 
    Collections.singleton((Collection<String>) null);

Set<? extends Collection<?>> anyCollectionSingleton = 
    Collections.singleton((Collection<?>) null);

What I can't explain is the last line. Why ? extends Collection<?> ? extends Collection<?> is used instead of simple Collection<?> ?

Is this a correct fix for this?

Set<Collection<?>> anyCollectionSingleton = 
    Collections.<Collection<?>>singleton((Collection<?>) null);

Why I started all this:

I had an issue with not compiling line:

java.util.Optional.ofNullable((Collection<?>) a).orElse((Collection<?>) b);

This seems to fix the issue, but what is the price?

java.util.Optional.<Collection<?>>ofNullable((Collection<?>) a).orElse((Collection<?>) b);

No, it's a completely different concept.

What is meant to be used with

Set<? extends Collection<?>> anyCollectionSingleton = 
Collections.singleton((Collection<?>) null);

is that you have a generic class that extends a Collection of generic classes.

So, it's about inheritance.

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