Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 08-26-2004, 06:03 PM   PM User | #1
Kernel_Mustard
New to the CF scene

 
Join Date: Aug 2004
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Kernel_Mustard is an unknown quantity at this point
Class Cast exception...strange outcome

so i was getting a class cast exception in part of my code (using Java 2 sdk 1.4.1). i added an exception handler and the following is the section of the code:

Object obj = _secondVector.get(i);
try{
Integer y = (Integer)obj;
_firstVector.set(y.intValue(), "<<<remove>>>");
}catch(ClassCastException e){
System.err.println("Cast Error Caught (change)");
System.err.println("Class is really: " + obj.getClass().getName());
e.printStackTrace();
}

_secondVector is simply of the Vector class. this, i thought returned an Object. However, the exception handler prints out:

Cast Error Caught (change)
Class is really: java.lang.String

can anyone shed some light on why obj is a String instead of an Object?

******edit******
i tried changing the line:

Integer y = (Integer)obj;

to:

Integer y = new Integer(obj);

Because it said that obj was actually a String and there is an Integer constructor with String as the argument, but i get:

cannot resolve symbol
symbol : constructor Integer (java.lang.Object)
location: class java.lang.Integer
Integer y = new Integer(obj);

So now it's telling me that obj is an object, and before that it was a string......?????

Last edited by Kernel_Mustard; 08-26-2004 at 06:15 PM..
Kernel_Mustard is offline   Reply With Quote
Old 08-29-2004, 09:12 AM   PM User | #2
shmoove
Regular Coder

 
Join Date: Dec 2003
Posts: 367
Thanks: 0
Thanked 0 Times in 0 Posts
shmoove is an unknown quantity at this point
A String is an Object too (well, everything except the primitive types is an Object in Java).

To use the Integer constructor that takes a String to need to cast the Object into a String:
Code:
Integer y = new Integer((String)obj);
Or, assuming that the Object is a String with a numeric value, it would be slightly more effective:
Code:
int y = Integer.parseInt((String)obj);
shmoove
shmoove is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:36 PM.


Advertisement
Log in to turn off these ads.