• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question on Whizlabs Test Question

 
Ranch Hand
Posts: 320
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's right. I forgot about Type Erasure having that effect. Thanks for reminding me!
 
permaculture is a more symbiotic relationship with nature so I can be even lazier. Read tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic