This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics wildcard declaration doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics wildcard declaration doubt" Watch "Generics wildcard declaration doubt" New topic
Author

Generics wildcard declaration doubt

sentil kumar
Ranch Hand

Joined: Oct 23, 2006
Posts: 74
public void addRectangle(List<? extends Shape> shapes) {
shapes.add(0, new Rectangle()); // Compile-time error!
}
here Rectangle is a subclass of Shape.
this method can be called with list of Rectangle object. but why the Rectangle object is not allowed to add shape reference.

is the bounded wildcards declaration is allowed only in the method declaration.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Originally posted by sentil kumar:
public void addRectangle(List<? extends Shape> shapes) {
shapes.add(0, new Rectangle()); // Compile-time error!
}
here Rectangle is a subclass of Shape.
this method can be called with list of Rectangle object. but why the Rectangle object is not allowed to add shape reference.

is the bounded wildcards declaration is allowed only in the method declaration.


You cannot add items to the list when the declaration is an upper-bounded wildcard.

The reason is there is no way for the compiler to check to make sure that the add is legal because there can be many subclasses of Shape.
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: Generics wildcard declaration doubt
 
It's not a secret anymore!