Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics 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" Watch "Generics" New topic
Author

Generics

joshua antony
Ranch Hand

Joined: Jun 05, 2006
Posts: 117


We do not get ClassCastException at runtime at here because generics is not applicable at runtime. Am I right?
[ October 19, 2006: Message edited by: Barry Gaunt ]
Petrus Pelser
Ranch Hand

Joined: Feb 20, 2006
Posts: 132
You may not get an exception at runtime, but you would not be able call a Circle (Compiler complains) or Rectangle (Runtime exception) specific method on an object in the list.
Aniket Patil
Ranch Hand

Joined: May 02, 2006
Posts: 218
ArrayList<Circle> a = new ArrayList<Circle>();
ArrayList b = a;
ArrayList<Rectangle> c = b //Here

Take a look at the change at "Here". It works even without the cast, to ensure compatibility with older versions.


SCJP 5.0 | SCWCD 1.4 <br /> <br />If you don't know where you are going, any road will take you there!
Sharmila Rishi
Greenhorn

Joined: Oct 11, 2006
Posts: 20
Hi Aniket,
According to your code


what you are implying is


how will it compile?
can you please explain.



-Sharmila Rishi.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Originally posted by Sharmila Rishi:
Hi Aniket,
According to your code


what you are implying is


how will it compile?
can you please explain.



-Sharmila Rishi.


The type information is lost when the raw ArrayList reference b is assigned to point to the ArrayList<Circle> created in the first line.
Sharmila Rishi
Greenhorn

Joined: Oct 11, 2006
Posts: 20
So the result would be



Am i right?
If yes, then can we add elements to the ArrayList..?

What will happen when the elements are read back?

Should we have to type cast it...?



-Sharmila Rishi.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Generics
 
Similar Threads
Generics
Whizlabs test question : Generics
Casting in generics. . .
Generics Casting
Generics