Error when casting from object to integer

imported java.lang.*;

I have delcared
Integer L, R;

tried this line:
L=new Integer(theStack.pop());
R=new Integer(theStack.pop());

when compiling i get this error:
cannot find symbol
symbol : constructor Integer(java.lang.Object)
location : class java.lang.Integer
L (or R)= new Integer(theStack.pop());
^

The only thing i can think of that may not be right is the fact that the data stored in the stack is
already type Int, and the casting is looking for type object. But i thought it shouldn't matter because of the higherarchy. What else could be wrong?

Comments

  • The class Integer has a constructor.

    you can go and look at the source code for this class and you will see that the constructor doesn't except an Object.

    you called on the Integer constructor when you did: new Integer(Object)

    so the command is not recodnized.
  • i see, so how would i cast an object to integer? i can't figure it out, Integer.parseInt only works for a string parameter. Any suggestions?
  • : i see, so how would i cast an object to integer? i can't figure it out, Integer.parseInt only works for a string parameter. Any suggestions?
    :

    since you are using a stack and you say the stack returns an object when you pop(), you should know that the compiler will have no idea what is really in the stack, so it is regarded to as some kind of Object.

    you will need to tell the compiler: "Trust me man, I know what I'm doing" when you try casting.

    so if you want to go over through all the items in the stack you'll do this:

    for (all items in the stack)
    if (item instanceof integer)
    do --> put the Integer into a variable

    use the "instanceof" - it tells the compiler to check if the item on the stack is really an instance of an integer, thus allowing you to cast.


  • If your stack contains Objects of type Integer, you can cast using:
    [code]
    Integer n = (Integer) stack.pop();
    [/code]
    Of course, if the Object isn't an instance of Integer, a ClassCastException will be thrown.

    You can get the type of an object from its class:
    [code]
    System.out.println( o.getClass().getName() );
    [/code]

    ---------------------------------
    [size=1]HOWTO ask questions: http://catb.org/~esr/faqs/smart-questions.html[/size]

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories