• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why isn't this generics based instantiation working?

 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first statement works, but the second one does not compile.



Why did they design generics in a way to disallow something that seems (to me at least) to be a clear cut case of polymorphism?

Thanks,
Yuriy
 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Yuriy,

consider the following small example. It shows what could happen if it would be allowed what you think.

I hope this gives some explanation why this would be bad and usually not what you want.

Marco
 
amitabh mehra
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here, polymorphism applies to the "base" i.e. the collection class and not to the generic.
If we compare this with polymorphism with arrays, then at runtime, JVM knows the type of arrays but in case of collection this information is not available because of type erasure. All the generic type info is removed during compilation.

Also, for arrays there is runtime exception - java.lang.ArraySortException available. Nothing of this sort in collections. So all checks are done at compile time.

Hence, at base type there can be polymorphism but not for generic type.

Hope this answers your question.
 
Campbell Ritchie
Sheriff
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More about this in the Java Tutorials. Look up bounded types and subtyping.
 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Heh Marco, I didn't think of that.
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
amitabh:- java.lang.ArraySortException available.

I think you meant ArrayStoreException.
 
amitabh mehra
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Nitesh Kant:

I think you meant ArrayStoreException.


ya .... sorry for the typo.. my bad
 
arulk pillai
Author
Ranch Hand
Posts: 3385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic