Java stack type required?


  • 0
    D

    I got "no compatible type" error when I was using "Stack stack=new Stack(); "
    After specifying "Stack<Integer> stack=new Stack<Integer>();". It works now. But why?

    This code works:

    public class Solution {
        public int evalRPN(String[] tokens) {
            if(tokens.length==1)
                return Integer.parseInt(tokens[0]);
            Stack<Integer> stack=new Stack<Integer>();
            for(int i=0;i<tokens.length;i++)
            {
                if(tokens[i].equals("+")||tokens[i].equals("-")||tokens[i].equals("*")||tokens[i].equals("/"))
                {
                    int y=stack.pop();
                    int x=stack.pop();
                    if(tokens[i].equals("+"))
                        stack.push(x+y);
                    else if(tokens[i].equals("-"))
                        stack.push(x-y);
                    else if(tokens[i].equals("*"))
                        stack.push(x*y);
                    else
                        stack.push(x/y);
                }
                else
                    stack.push(Integer.parseInt(tokens[i]));
            }
            return stack.pop();
        }
    }

  • 0
    B

    stack.pop() is an object
    they cant be cast to int

    if you want Stack() use

    int y=(Integer)stack.pop();
    int x=(Integer)stack.pop();
    

    however, it is not a good practice


  • 0
    X

    perhaps you can use this function
    {stack.pop().intValue()}


  • 1

    The stack is a generic, so you must specify what type of data you will be using, if your don't then it will just be of type Object where you must cast it whenever you wish to use one of the values.

    if you do: Stack myStack=new Stack();
    then: int x = myStack.pop() will be wrong since myStack.pop() would be returning an object of type Object and you would have to cast it by doing: int x = (Integer)myStack.pop()

    But now if you specify the data type by doing: Stack<Integer> myStack=new Stack<Integer>(); then you CAN do int x = myStack.pop() since myStack.pop() will return an object of type Integer.

    Also, Java has auto-unboxing and boxing where Integers are automatically converted to int.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.