Search code examples
javadeque

return result of Deque pollFirst() in java


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


Solution

  • 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.