aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics" Watch "Generics" New topic
Author

Generics

meera kanekal
Ranch Hand

Joined: Feb 13, 2005
Posts: 75
Hi,
I was reading the Generics tutorial from the link posted by Ankit, and I have a question.
In the following code:

import java.util.*;
class Person {

}
class Driver extends Person {

}
public class Census {

public static void addRegistry
(Map<String, ? extends Person> registry){
//registry.put("s", new Driver()); line 1
registry.put("s", new Person());// line 2
}
public static void main(String[] args) {
Census c = new Census();
Map<String, Driver> allDrivers = new HashMap<String, Driver>();
c.addRegistry(allDrivers);
}

}

For line 1 you get a compiler error which is understandable because you cannot put anything since the compiler is not sure what you are inserting. But what about line 2? I am inserting a Person. So why does compilation fail?

Thank you all in advance.
Meera
Rekha Srinath
Ranch Hand

Joined: Sep 13, 2008
Posts: 178
With ? extends, you cannot add anything. You have to use ? super to add something to the collection...that too, addition can be done only based on the condition specified in ? super
meera kanekal
Ranch Hand

Joined: Feb 13, 2005
Posts: 75
Thanks Rekha for your explanation.
Meera
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics