Question about generics: wildcard super

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
The_Nick
Posts: 132
Joined: Thu May 16, 2013 9:23 am
Contact:

Question about generics: wildcard super

Post 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.

admin
Site Admin
Posts: 10078
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Question about generics: wildcard super

Post 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
If you like our products and services, please help us by posting your review here.

The_Nick
Posts: 132
Joined: Thu May 16, 2013 9:23 am
Contact:

Re: Question about generics: wildcard super

Post 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.

Post Reply

Who is online

Users browsing this forum: No registered users and 28 guests