File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies 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: 18114
    
    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
Casting relation
Clarification about ? super Object
The use of ? extends
ArrayList.indexOf
Sierra/Bates, Chapter 7, Two Minute Section