File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Generic Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Make it so: Java DB Connections & Transactions this week in the JDBC forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generic" Watch "Generic" New topic


meeta gaur
Ranch Hand

Joined: Dec 05, 2012
Posts: 305 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".

My one regret in life is that I am not someone else.
- Woody Allen
Paul Clapham

Joined: Oct 14, 2005
Posts: 19891

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.
I agree. Here's the link:
subject: Generic
It's not a secret anymore!