In Java generics, what is List <? super String> means?

Can someone explain how this can be compiled and how it works?

List<? super String> list = new ArrayList<Object>(); 

As I understand it, the execution of this should be either a string list or a list of objects that have String as a superclass? Did I miss something?

+6
source share
3 answers

No (i.e. yes, you missed something :-). <? super String> <? super String> - any class that is a superclass of String (including String itself). (In this case, the only other suitable class is Object .)

What you described will be <? extends String> <? extends String> (which is not very useful in this particular case, since String is final , so it cannot have any subclasses).

+20
source

<? super String> <? super String> accepts String and any superclass.

Do not confuse with:

<? extends String> <? extends String> accepts String and any subclass (which is not, since String is final ).

+3
source

Since String is final , it cannot be a superclass of any other class. List<? super String> List<? super String> means any type that is a super-class of String . In fact, Object is a superclass of String (of any class).

0
source

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


All Articles