aspose file tools*
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
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: 18570
    
    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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How Does the Compiler Know Not To Allow Adding to a Generic List With a Wildcard?