| 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
Bartender
Joined: Sep 08, 2007
Posts: 2946
|
|
|
Did you try executing?
|
Mohamed Sanaulla | My Blog
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3859
|
|
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: 19230
|
|
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
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: Generics Problem
|
|
|