SHUYU LYU SHUYU LYU - 4 months ago 26
Java Question

Stack.peek() method is really confusing

I have a code snippet

public class Pattern {

public static void main(String[] args) {
MinStack obj = new MinStack();
obj.push(-124);
obj.push(-164);
obj.pop();
obj.push(10);
int a=obj.getMin();
System.out.println(a);
}
}
class MinStack {
Stack<Integer> s;
Stack<Integer> minS;
int min;
public MinStack() {
s=new Stack();
minS=new Stack();
min=Integer.MAX_VALUE;
}

public void push(int x) {
//if(minS.isEmpty()||minS.peek()>x)
if(min>x)
min=x;
minS.push(min);
s.push(x);

}

public void pop() {
int a=minS.peek();
int b=s.peek();
*Here*
boolean c=a==b;
if(minS.peek()==s.peek()){
minS.pop();
s.pop();
if(!minS.isEmpty()){
min=minS.peek();
}else
min=Integer.MAX_VALUE;
return;
}

minS.pop();
s.pop();

if(minS.isEmpty())
min=Integer.MAX_VALUE;
}

public int top() {
return s.peek();
}

public int getMin() {
return minS.peek();
}
}


I use the
Here
tag for you to quick locate the confusing part. When I debug the code,
if(minS.peek()==s.peek())
is false but the value of both is the same.
The I use
int a=minS.peek();int b=s.peek();int c=a==b;if(c)
to replace the part, it is true now. It really confuses me cause I do not know why comparing two same numbers yields to
false
. Any ideas is appreciated.

Answer

This is caused by the difference between int and Integer. Integer is a reference type. minS.peek()==s.peek() compares Integers. Comparing Integers is true, iff they reference the same Integer object. However, if you first assign minS.peek() and s.peek() to int typed variables and compare the int values afterwards, you no longer compare references but the actual values. This is, because the assignment unboxes the Integer references to int. You can resolve this by replacing the reference comparison minS.peek()==s.peek() by an equality check: minS.peek().equals(s.peek()).