wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Using ? super and wildcard Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Using ? super and wildcard" Watch "Using ? super and wildcard" New topic
Author

Using ? super and wildcard

Tom Scott
Greenhorn

Joined: Aug 18, 2006
Posts: 21
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

Joined: Dec 28, 2006
Posts: 81
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.


SCJP 1.5<br />SCWCD 1.4
sentil kumar
Ranch Hand

Joined: Oct 23, 2006
Posts: 74
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using ? super and wildcard