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 How Does the Compiler Know Not To Allow Adding to a Generic List With a 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 "How Does the Compiler Know Not To Allow Adding to a Generic List With a Wildcard?" Watch "How Does the Compiler Know Not To Allow Adding to a Generic List With a Wildcard?" New topic
Author

How Does the Compiler Know Not To Allow Adding to a Generic List With a Wildcard?

Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 688

How does the compiler know to flag an error when you try to add an element to a generic list when the generic involves a wild-card?



The above code is one of the questions from K&B Practice Exams Practice Exam #3, question #33
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

The definition of that method is

and the definition of the type is

So in the context of "List<? extends Dog>", the compiler (conceptually) treats the method as "public boolean add(? extends Dog e)". Since it doesn't know what type "? extends Dog" is going to represent, it can't accept a Collie object at that point.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How Does the Compiler Know Not To Allow Adding to a Generic List With a Wildcard?
 
Similar Threads
ArrayList.indexOf
Casting relation
The use of ? extends
Clarification about ? super Object
Sierra/Bates, Chapter 7, Two Minute Section