0

I was coding an algorithm issue, below code can't pass case

public void pop() {
    if (s1.pollFirst() == minStack.peekFirst())
        minStack.pollFirst();
}

however below can,

public void pop() {
    int tmp = s1.pollFirst() ;
    if (tmp == minStack.peekFirst())
        minStack.pollFirst();
}

the only difference is how I use s1,pollFirst() return result. I can't figure out real difference here. Thanks

nathan
  • 754
  • 1
  • 10
  • 24

1 Answers1

5

Comparing two Integer Objects with values less than -128 or bigger than 127 using == will always result in false. However, if you compare Integer with primitive int, it will give you true if the actual value is the same.

        int n1=128;
        Integer n2=127;
        Integer n3=127;
        Integer n4=128;
        Integer n5=128;
        System.out.println(n1==n2); //false
        System.out.println(n2==n3); //true
        System.out.println(n4==n5); //false
        System.out.println(n1==n5); //true

In the second example you are assigning the value to the primitive int, therefore it is automatically unboxed.

wisnix
  • 180
  • 1
  • 8
  • please add tags – Bokris Itzhak Jan 14 '20 at 21:38
  • It will not “always” result in false. Integer objects outside of the -128, 127 range are not *guaranteed* to be cached instances, but Java implementations are *permitted* to cache values outside of that range. What matters is that it’s not guaranteed, so it’s generally not safe to compare Integer objects with `==`. – VGR Jan 14 '20 at 22:59