This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
It shows compliation error:
cannot find symbol: add(int,Gen1)
That is all it shows? Are you sure? What JDK are you using?
I have executed it. I am using jdk 7 .
According to theory, its correct. But practically it is not happening .
Are you using an IDE? Here is the error I see trying to compile it on the command line and in NetBeans. What do you think the problem is?
Gen1.java:7: error: unexpected type
Vector<? extends Object> v1=new Vector<? extends Object>();
required: class or interface without bounds
found: ? extends Object
Gen1.java:8: error: no suitable method found for add(int,Gen1)
method Vector.add(int,CAP#1) is not applicable
(actual argument Gen1 cannot be converted to CAP#1 by method invocation co
method Vector.add(CAP#1) is not applicable
(actual and formal argument lists differ in length)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ? extends Object
If you want a list that can contain any subtype of Object, then what you need is simply a List<Object>.
A List<? extends Object> is something else. It's a variable that can reference any List<X>, where X is a specific type that is a subtype of Object. So all these are valid statements:
So...what objects do you think the compiler can safely allow you to add into all of those? You're trying to add a Gen1. That's fine if it's a List<Object> or a List<Gen1>, but what if it's one of the others? There's nothing that can be safely added to all of them*, so the compiler won't allow it.
(* More specifically, the only thing that can be safely be added to all of them is "nothing" - it will allow list.add(null))
On the right side of the = you cannot have a type with a wildcard. In other words, you cannot do new Vector<? extends Object>();, instead of ? extends Object you'll need to use a specific type, and not something with a wildcard.