This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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 Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Using ? super and wildcard" Watch "Using ? super and wildcard" New topic

Using ? super and wildcard

Tom Scott

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?


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.
subject: Using ? super and wildcard
Similar Threads
Collections and me...
Generics question from bonus exam
Generics problem- why not taking Animal, Object and super of Dog
Help me fix this-Part-2,so I can compile(generics doubt)