Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics wildcard declaration doubt  RSS feed

 
sentil kumar
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!