Win a copy of 97 Things Every Java Programmer Should Know this week in the Java in General forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • salvin francis
  • fred rosenberger

Question on Whizlabs Test Question

Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following is from a Whizlabs Diagnostic Exam

Just to focus on the problem, the official answer given says that there is
no ClassCastException at runtime.

I would think that there is and I'll explain why I think so.
Line1 (ArrayList b = a) is taking an ArrayList<Circle> and assigning it
to an ArrayList raw reference. That I can live with.
The next line casts b to an ArrayList<Rectangle> and puts it into c, an ArrayList<Rectangle> reference. So I have taken what is actually an
ArrayList<Circle> and stuffed it into an ArrayList<Rectangle> reference by
casting it. Fine! I can see that would get through the compiler but, at
runtime, I would think that the JVM would realize that the true type of b is an ArrayList<Circle> and throw a ClassCastException.

Okay..... what am I missing?

[ September 05, 2008: Message edited by: Bob Ruth ]
Posts: 9671
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you write ArrayList<Circle> the compiler will remove the <Circle> from this statement. This is called type erasure. So actually the JVM doesn't know that you are assigning ArrayList<Circle> to ArrayList<Rectangle>. for the JVM they are just ArrayList. that's it, the JVM doesn't know about the type of the ArrayLists.
Bob Ruth
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's right. I forgot about Type Erasure having that effect. Thanks for reminding me!
He was expelled for perverse baking experiments. This tiny ad is a model student:
Devious Experiments for a Truly Passive Greenhouse!
    Bookmark Topic Watch Topic
  • New Topic