• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why this compilation error(Generics)  RSS feed

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using Generics



Why this statement gives compilation error ?

What I thought was that you cannot convert ArrayList of type oblject to type string. But the counter question was why it can't convert, as Object class is superclass of all classes ?

What would be the proper explanation for this?
 
Rancher
Posts: 1776
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is List<Object> a supertype of List<String>?

No, different instantiations of the same generic type for different concrete type arguments have no type relationship.
It is sometimes expected that a List<Object> would be a supertype of a List<String> , because Object is a supertype of String . This expectation stems from the fact that such a type relationship exists for arrays: Object[] is a supertype of String[] , because Object is a supertype of String . (This type relationship is known as covariance .) The super-subtype-relationship of the component types extends into the corresponding array types. No such a type relationship exists for instantiations of generic types. (Parameterized types are not covariant.)


Source - Angelika Langer - Generics FAQ
 
Simranjeet Chawla
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks John. Useful Link for FAQ.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!