• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Generics (again)

 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Line (1) (as expected) caused a compile error "Incompatible types".
Line (2) (as expected) executed sucessfully

Line (3) executed successfully.
But why ? I was expecting a compile error because although Integer is a subclass of Number , <Integer> is not a subclass of <Number>.
Thank you.
 
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Actually what you can't do is to declare :

List <Number> numList = new ArrayList <Integer>

but you are allowed to hold Integer values in <Number> List.

See Chapter 7 of SCJP 6 Study Guide Book. Page 613 says:

"(...) So here, we're using polymorphism not for the object that the array
reference points to, but rather what the array can actually HOLD - in this case, any
subtype of Animal. You can do the same thing with generics:



So this part works with both arrays and generics collections - we can add an
instance of a subtype into an array or collection declared with supertype.
(...)
"

Hope this helps,
Paul
 
Marshal
Posts: 80653
476
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
More complicated than the average beginner's question. Moving
 
Campbell Ritchie
Marshal
Posts: 80653
476
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Whenever you have generics problems, find the Java Tutorials and Angelika Langer's generics FAQ (I haven't got this link at the moment). There is something in the Java Tutorials about Cage<Lion>s and Cage<Butterfly>s which is similar to your problem.
[ December 30, 2008: Message edited by: Campbell Ritchie ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic