• 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

Class Cast Exception

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I got a "java.lang.ClassCastException" when I try to do the following:



I understood that this Exception is thrown because of the fact that Cast should have been '(String)'.

But can any one tell me if the 'get()' method of Vector returns 'a simple Java Object', why doesn't the compiler allow '(Integer)' that extends a Java Object?
How does the JRE determines the type of Cast allowed ?

thanks in advance,

Ravi.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First, the cast shouldn't be (String), it should be (StringBuffer), of course.

Second, a cast of a reference type is only a hint to the compiler that an object is of a certain type; it's not a conversion operator. The real object in the Vector is a StringBuffer, and not an Integer, so it can't be cast to Integer. It's as simple as that.

The JVM "knows" the real type of every object; the details are implementation specific, but generally every object will contain a reference to its Class object or a data structure representing its Class.
 
Ravi Tripura
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Ravi Tripura:
Hi,
I got a "java.lang.ClassCastException" when I try to do the following:



I understood that this Exception is thrown because of the fact that Cast should have been '(String)'.

But can any one tell me if the 'get()' method of Vector returns 'a simple Java Object', why doesn't the compiler allow '(Integer)' that extends a Java Object?
How does the JRE determines the type of Cast allowed ?

thanks in advance,

Ravi.




Hi Ernest,

I have added the following statement to my code:

System.out.println(v.get(0).getClass());

and got the class type information of the object.

thanks very much for the information,

Ravi.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic