Java Generics with Wildcards and Static Wrappers

Excuse me for such a general title for the question, but was not sure how to correctly name your question.

See the default call types of Collections.singleton by default:

 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 cannot explain is the last line. Why ? extends Collection<?> ? extends Collection<?> used instead of simple Collection<?> ?

Is this the correct fix for this?

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

Why I started all this:

I had a problem with a non-compiled string:

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

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

 java.util.Optional.<Collection<?>>ofNullable((Collection<?>) a).orElse((Collection<?>) b); 
+5
source share
1 answer

No, this is a completely different concept.

What is supposed to be used with

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

is that you have a generic class that extends the collection of generic classes.

So this is about inheritance.

0
source

Source: https://habr.com/ru/post/1240673/


All Articles