File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting in 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 "Casting in generics. . ." Watch "Casting in generics. . ." New topic

Casting in generics. . .

Rahul Nair
Ranch Hand

Joined: Dec 01, 2007
Posts: 138
class Shape{}
class Circle extends Shape{}
class Rectangle extends Shape{}

class generics4

ArrayList<Circle> a = new ArrayList<Circle>();
a.add(new Circle());
ArrayList b = a;
ArrayList<Rectangle> c = (ArrayList<Rectangle> b;
c.add(new Rectangle());

for(Object o : b)

This is a example form whizlab...

they said the program compiles with warnings and prints some output at runtime...


ArrayList<Rectangle> c = (ArrayList<Rectangle> b;

here b is non generic ArrayList which initialized to the ArrayList<circle> when declared.

so i think there is an compiler error at this line because


So it is correct ???
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Hi Rahul,

Why don't you try the code with your compiler to test your hypothesis? A big part of successful SCJP preparation is writing and running code, so you should simply try to run the program if you're not sure what it's behavior will be.

After that, you can come back here to ask for an explanation of the behavior you observed, if necessary.
[ December 04, 2007: Message edited by: Kelvin Lim ]

SCJP 5.0
Rahul Nair
Ranch Hand

Joined: Dec 01, 2007
Posts: 138
hi Kelvin,
Thanks for reply...
I already compile this program with javac -Xclint command line

it shows 1 warning,of unchecked cast...

but, i don't understand why this give warning even if we cast totally different type...

Instead, It has to show an error of undefined casting at compile time becouse,Generics checked at compile time, But compiler shows a warning...

if i consider,This is happen becouse of non generic list 'b' but b's content are of type circle....

So,Why it allows to cast ???


Rahul. . .
I agree. Here's the link:
subject: Casting in generics. . .
jQuery in Action, 3rd edition