Home > Software engineering >  Conditional Clauses not working as Expected
Conditional Clauses not working as Expected

Time:08-14

I am facing trouble with the following piece of code. values and minStack are both stacks initialised, and the top values of both the stacks are same. However, the first code snippet fails to go into the if condition while the latter does. I am unable to debug this.

   public void pop() {

        System.out.println(values.peek()); // prints -1024
        System.out.println(minStack.peek()); // prints -1024

        if(values.pop() == minStack.peek()) { 
        // Condition not fulfilled
            minStack.pop();
        }
    }

However, the following works as expected.

    public void pop() {
        int valTop = values.pop();
        int minTop = minStack.peek();

        if(valTop == minTop) { 
             minStack.pop();
        }   

    }

Please help as I am unable to figure out the reasoning behind it.

CodePudding user response:

You (probably) have the stacks initialized as Stack<Integer>, that means they store Integer instances. Integer is an object (notice the uppercase I) and comparing two object instances using == compares their addresses in memory. Not what you want. new Integer(1) != new Integer(1) as you are creating two objects which obviously don't point to the same memory address.

On the other hand, using == to compare two primitives compares their value, not their address.

You might want to change the stack initializations to be Stack<int>, but you can't do that (yet) as generics in Java can't be primitive.

To fix this, use the overriden .equals(Object obj) method in Integer which calls .intValue() on both Integer objects and actually compares two ints.

So, replace

if(values.pop() == minStack.peek())

with

if(values.pop().equals(minStack.peek()))

The second example works because when you assign an Integer object to a variable of type int, the Integer is automatically converted to int. The opposite can also be done via the process of autoboxing.

CodePudding user response:

You are comparing object references with ==. Use

if (values.pop().intValue() == minStack.peek()) {

or

if (values.pop().equals(minStack.peek())) {
  • Related