Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting in generics. . .

 
Rahul Nair
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Rahul Nair
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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. . .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic