Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Aug 2004
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    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 07:15 PM.

  • #2
    Regular Coder
    Join Date
    Dec 2003
    Posts
    367
    Thanks
    0
    Thanked 0 Times in 0 Posts
    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


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •