Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Kaydell Leavitt
Ranch Hand
Posts: 689
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 20758
30
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic