1
public void pop() {
    int a = stack.peek();
    int b = min.get(min.size()-1);
    System.out.println("a:"+a+" "+"b:"+b);
    if (a==b) {
        System.out.println("111");
    }
    if (stack.peek()==min.get(min.size()-1)) {
        System.out.println("222");
    }
    stack.pop();
}

I created a class called MinStack, here is the pop(), the variable stack is a Stack(Integer), and min is an ArrayList(Integer), but the second if stmt is not always working correctly.

I got console like this:

a:512 b:-1000
a:-1000 b:-1000
111
a:-1000 b:-1000
111

I think the "111" and "222" will always show together, but here is not. If I change the second if stmt as stack.peek()-min.get(min.size()-1)==0, then it works correctly, why this happened?

Thanks in advance.

EDIT:

I know where is wrong, I have to use stack.peek().intValue()==min.get(min.size()-1).intValue(), cause they are Integer.

Georgey
  • 115
  • 1
  • 6

1 Answers1

0

This is an issue of Integer comparison. stack.peek and min.get(min.size()-1) both return Integers. Even though they contain the same int value, they are not the same Integer instance, so the comparison returns false.

Change your code to :

if (stack.peek().equals(min.get(min.size()-1))) {
    System.out.println("222");
}

The alternative comparison stack.peek()-min.get(min.size()-1)==0 returns true because here you are comparing two int primitives.

Eran
  • 387,369
  • 54
  • 702
  • 768