*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics Help please ! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics Help please !" Watch "Generics Help please !" New topic
Author

Generics Help please !

jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
The below gives me error :


However , this doesnt give me error :



Why so, could someone please explain ?
Ryan Hamilton
Greenhorn

Joined: Apr 13, 2009
Posts: 4


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

Joined: Mar 22, 2010
Posts: 308

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


SCJP6, SCWCD5, OCP-JBCD5, OCE-JWSD6 OCE-JPAD6 , OCM-JEA5 1,OCM-JEA5 2,3 - Brainbench certifications: J2EE, Java2, Java2-NonGUI, JSP, SQL2000 Admin, SQL2000 Programming , Brainbench certified Java Programmer, Computer Programmer, Web Developer, Database Administrator
Flavio Luiz Maria
Greenhorn

Joined: May 17, 2010
Posts: 6
You also can to do:



In this method you can add all objects that extends Animal


Sun Certified Java Programmer 6.0
Rajeev Rnair
Ranch Hand

Joined: Mar 22, 2010
Posts: 308

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

Joined: Apr 13, 2009
Posts: 4
Why does java allow implicit casting of array subtypes?
Particularly when it doesn't allow similar behavior for collections?

ujjawal rohra
Ranch Hand

Joined: Mar 20, 2010
Posts: 105
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


SCJP 6
 
Consider Paul's rocket mass heater.
 
subject: Generics Help please !
 
Similar Threads
generics extends question?
Generics problem- why not taking Animal, Object and super of Dog
wildcards in generics
Generics Question
Generics - super