Question about min.peek() == stack.peek()


  • 0
    S

    In my original code, I wrote this,which can't match even they have the same value.

    public void pop() {
            if(min.peek() == stack.peek())
                min.pop();
            stack.pop();
        }
    

    until I changed it like this, it works good.

    public void pop() {
            int minV = min.peek();
            if(minV == stack.peek())
                min.pop();
            stack.pop();
        }
    

    Could anyone told me why the first way does't work?


  • 1

    min.peek() returns one object reference and stack.peek() returns another object reference .

    == will not evaluate to true since both object references have different memory addresses.

    minV == stack.peek() evaluates to true because compiler implicitly does unboxing from wrapper class to its respective primitive type . Refer here for autoboxing and unboxing


Log in to reply
 

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