my dog learned polymorphism*
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
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: 3071
    
  33

Did you try executing?


Mohamed Sanaulla | My Blog
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4422
    
    8

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: 19723
    
  20

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
 
jQuery in Action, 2nd edition
 
subject: Generics Problem