Java: why need int cast


  • 2
    W
    class MinStack {
    Stack<Integer> stack = new Stack<Integer>();
    Stack<Integer> min = new Stack<Integer>();
    
    public void push(int x) {
        stack.push(x);
        if (min.empty()) {
            min.push(x);
        } else if (x <= min.peek()) {
            min.push(x);
        }
    }
    
    public void pop() {
        if (!stack.empty()) {
            System.out.println(stack.peek() == min.peek());
            if (!min.empty() && (int)stack.peek() == (int)min.peek()) {
                min.pop();
            }
            stack.pop();
        }
    }
    
    public int top() {
        if (!stack.empty()) {
            return stack.peek();
        } else {
            return -1;
        }
    }
    
    public int getMin() {
        if (!min.empty()) {
            return min.peek();
        }
        return -1;
    }
    

    }

    Is there anyone know why should use cast here (int)stack.peek() == (int)min.peek()?
    Thanks!


  • 7
    Z

    stack.peek() will return an Integer object. If you want to compare whether the value of two objects are equal, you should use object1.equals(object2).

    If you use object1 == object2, it's actually comparing whether the two references are pointed to the same object.

    However, we can use == to compare the value of two primitive type variables. So, we have two options here, use object.equals() or cast Integer to int and use ==


Log in to reply
 

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