Page 1 of 1

Question about generics: wildcard super

Posted: Mon Jul 08, 2013 5:21 am
by The_Nick
Hi,
I have a question regarding generics:

Code: Select all

Map<? super String, ? super String> mappa1 = new HashMap<Object,Object>();
with super it's possible to instantiate a HashMap<Object,Object> for a <? super String>.
However then you can add only objects which extends String ( in this case only String itself).
Why don't they forbid by compilation error as well as happens with the "extends" wildcard.
I mean if once created a map of Object, Object and then it's possible only to add Strings.. why not forcing to create a map of String, String in the first place?

Thanks a lot in advance.


The_Nick.

Re: Question about generics: wildcard super

Posted: Mon Jul 08, 2013 6:20 am
by admin
Because there could be a situation where you want to make sure that only the objects of subclass of String are added to the map. String, obviously, is a bad example because it is final but the concept is same.

When to use ? super or ? extends depends on what you want to be able to add or take out from the collection. Please go through this for more details: viewtopic.php?f=2&t=473

Re: Question about generics: wildcard super

Posted: Mon Jul 08, 2013 10:27 am
by The_Nick
I understand that. However I do not understand why it is allowed.
I mean I understand that there could be certain situations where you would want only to add subtypes of a certain class. However why would you want a collection with super type and sub type and wanting to add only subtypes? mmm now that I am thinking of it, it might be to guarantee polymorphism. Is that correct?

Thanks in advance.

The_Nick.