• 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 ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

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 ]
 
Sheriff
Posts: 9643
42
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!
 
If you like strawberry rhubarb pie, try blueberry rhubarb (bluebarb) pie. And try this tiny ad:
professionally read, modify and write PDF files from Java
https://products.aspose.com/pdf/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!