Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics Help please !

 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The below gives me error :


However , this doesnt give me error :



Why so, could someone please explain ?
 
Ryan Hamilton
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


For primitives, the compiler knows that Dog is a subtype of Animal, and that Dog[] is a subtype of Animal[], for generics this is not the case.

As to why java allows implicit casting of array subtypes, which can then cause the error shown, I am not sure.
 
Rajeev Rnair
Ranch Hand
Posts: 310
1
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
jose chiramal wrote:The below gives me error :





Hi Jose,

First of all your code (1st) will NOT give compile error, it gives a RuntimeException though!
The reason is you are trying to put a Dog() into a Cat[]. Dog is NOT a Cat , so that gives an Exception. It compiles fine because both are sub classes of Animal
 
Flavio Luiz Maria
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You also can to do:



In this method you can add all objects that extends Animal
 
Rajeev Rnair
Ranch Hand
Posts: 310
1
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Flavio Luiz Maria wrote:You also can to do:



In this method you can add all objects that extends Animal

Hi Flavio, welcome to the ranch!
yes, you are right! you can add all subclasses of Animal to the above method. So you can add a Dog() or a Cat()

hope this helps!

 
Ryan Hamilton
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does java allow implicit casting of array subtypes?
Particularly when it doesn't allow similar behavior for collections?

 
ujjawal rohra
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is because there is an Exception for arrays--ArrayStore Exception while Generics are only a compile time protection with no run time exception.

That is, the line

List<Number> l=new ArrayList<Number>();
is only checked at compile time. At run time it becomes

List l=new ArrayList();

And if you are allowed to add a Float into Integer list at compile time just imagine what will happen to your code at run time
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic