This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics

 
meera kanekal
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rekha for your explanation.
Meera
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic