• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic

 
meeta gaur
Ranch Hand
Posts: 305
Notepad Tomcat Server Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

AnimalDoctor6.java:12: error: no suitable method found for add(Object)
animals.add(new Object());
^
method List.add(int,CAP#1) is not applicable
(actual and formal argument lists differ in length)
method List.add(CAP#1) is not applicable
(actual argument Object cannot be converted to CAP#1 by method invocation conversion)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object super: BigCat from capture of ? super BigCat
1 error

Why i can't add "Object" ? ,that is a super of "BigCat".
 
Paul Clapham
Sheriff
Posts: 21322
32
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have the usual misunderstanding regarding generic wildcards. When you write "List<? super BigCat>" that means that at runtime, an instance of that type will be an instance of List<X> where X is some supertype of BigCat. It does NOT mean that an instance of that type can contain any object of any supertype of BigCat.

So in your example, an instance of List<? super BigCat> could be a List<Animal>, since Animal is a supertype of BigCat. And you can't add an Object to a List<Animal>. So the compiler rejects that line of code.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic