Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics Problem

 
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
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you try executing?
 
Matthew Brown
Bartender
Posts: 4567
8
  • 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
Pie
Posts: 20527
54
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic