This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Generics Problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics Problem " Watch "Generics Problem " New topic
Author

Generics Problem

Rajul Konkar
Greenhorn

Joined: Nov 05, 2008
Posts: 20

Can anyone explain me why does 1st scriptlet fails and 2nd works,

Thanks in advance

Only pioneer take the untraveled path

Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3064
    
  33

Did you try executing?


Mohamed Sanaulla | My Blog
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4342
    
    7

Ignore for the moment the fact that String is a final class, and imagine we have a subclass MyString. And we have something like this:
Now, that would be allowed according to the first version of your method. But then you're adding a String to a list that can only take MyStrings. You've broken type safety. Which is why, whenever you have a List<? extends Something> as a method argument, you can't add anything to it within the method. The compiler can't guarantee that it's safe.

In the second case, the compiler knows inside the method that adding a String is completely safe.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

Matthew Brown wrote:Which is why, whenever you have a List<? extends Something> as a method argument, you can't add anything to it within the method. The compiler can't guarantee that it's safe.

Anything except null that is.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
 
subject: Generics Problem
 
Similar Threads
(GWT) Forcing SuggestBox to display its values
? extends String
Why generics work in that strange way?
Generic method