Paul Paul - 6 months ago 10x
Java Question

Java Stack Functions Diffrernce

I was trying to solve a light coding problem here:

But I don't know why the code below are not identical:

public void pop() {
// if (!minStack.isEmpty() && minStack.peek() == stack.peek()){
// minStack.pop();
// }
// stack.pop();
int x = stack.pop();
if (!minStack.isEmpty() && x == minStack.peek()) {

When I use the commented code, it goes wrong. Why is that?

Thank you so much!


If you had stacks of primitives, both should work because you would be comparing contents using the ==.

I am assuming you have stack of type Integer in which case the == checks for reference equality while you should check for value equality. Using a .equals() might just solve your problem. :)