• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics Problem  RSS feed

 
Rajul Konkar
Greenhorn
Posts: 20
Android Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone explain me why does 1st scriptlet fails and 2nd works,

Thanks in advance
 
Mohamed Sanaulla
Bartender
Posts: 3185
34
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you try executing?
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!