This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one 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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript 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: 689

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.
 
Consider Paul's rocket mass heater.
 
subject: How Does the Compiler Know Not To Allow Adding to a Generic List With a Wildcard?