aspose file tools*
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting in generics. . ." Watch "Casting in generics. . ." New topic
Author

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)
System.out.ptirnln(o);
}


This is a example form whizlab...

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

but,

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

" WE CAST A CIRCLE TYPE LIST TO RECTANGLE TYPE LIST "


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 ???

Thanks.

Rahul. . .
 
Don't get me started about those stupid light bulbs.
 
subject: Casting in generics. . .