File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using ? super and wildcard

 
Tom Scott
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the code below I was surprised that I couldn't add an Animal to the List at the line indicated in the comment.

Can anyone clarify the rules here? From what I could see it is legal to pass any kind of list of objects where these objects are Dogs or supertypes of Dog, but it is only legal to add an actual Dog to the list.

So where we say ? super <class> can I assum the general rule that I can only add <class> objects to the collection even though the collection may be typed on a super type?

Or has something else gone wrong?

Thanks,
Tom

 
Priya Viswam
Ranch Hand
Posts: 81
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public void addAnimal2(List<? super Dog> animals)

For this function declaration, you can pass Dog or any of its super types.
But inside the function you can add only Dog or its subtypes.
 
sentil kumar
Ranch Hand
Posts: 74
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why animals.add(new Animal()) is not allowed ?

if animals is pointing to new ArrayList<Dog>() and try to add new Animal() will lead to run time exception.
only lower bound class object only can be added in the animals reference.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic