• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Wildcards and generics

 
Greenhorn
Posts: 18
C++ Suse Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Reason: Since all entries contained in shapelist are of type Object, Any instance added to this list gets upcast'd into Object and that is ok.



Reason: An instance added to shapeList2 can be any subtype of Shape, shapeList2 is only supposed to contain only Rectangles. Compiler thus complains



Reason: An instance added to shapeList3 can be any subtype of Object, shapeList3 is only supposed to contain only Rectangles Compiler thus complains

Am I on correct track of reasoning about the above code fragments?

Thanks,
Divyanand
 
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The first one: Your list is a List of some class X which is a superclass of Shape. The compiler doesn't know what X is. However since Rectangle is a subclass of Shape, it must also be a subclass of X, and therefore a Rectangle is an X. Since it's a List<X>, you can therefore add a Rectangle to it.

The third one: Your list is a List of some class X which is a subclass of Object. The compiler doesn't know what X is. As far as the compiler knows, X could be String for example. And since it can't demonstrate that Rectangle is a subclass of this unknown X type, you can therefore not add a Rectangle to that List.

The second one is the same as the third one.
 
Ranch Hand
Posts: 89
1
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would suggest you to use your own generic type, not these types, that are provided by Java Collections API. Have you seen this site? I found it quiet useful. You may even download this FAQ as a .pdf file. Here is the answer on the question, similar to yours.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic