• 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
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

ClassCastException in Generic code

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is my custom code based upon Question 62 from ExamLab Diagnostic Test.

Above code runs fine. But when I change line 15 from

to

Now it started throwing ClassCastException. Why is so? Is this due to generic code removed from byte code during compilation means generic code provide compile time safety not runtime?

Is this SCJP level of question?
 
Ranch Hand
Posts: 5575
Eclipse IDE Windows XP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


if you are using generic it doesnt mean that you wont get ClassCastException. it depends on your programming
 
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ClassCast exception is thrown at runtime.
and all Genrics type information is removed at compile time so at runtime collections are collections like earlier days i.e befor jdk1.5 versions
and why you getting exception is explained by above post
 
Pradeep Kr
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Seetharaman Venkatasamy wrote:

if you are using generic it doesnt mean that you wont get ClassCastException. it depends on your programming



I understand why ClassCastException is coming. I am trying to make sense of this and trying to understand what is the ideal solution for this.

One more thing - ClassCastException comes only when assigning result of as.get() to C. If you execute as.get() and does not assign it to anything there is no ClassCastException. That means there is no casting being done if we don;t assign result to any variable?

 
If somebody says you look familiar, tell them you are in porn. Or in these tiny ads:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic