lundi 29 juin 2020

'If' condition doesn't work with the stack pop and peek methods inside the if condition in java

    Stack<Integer> st = new Stack<Integer>();
    Stack<Integer> st2 = new Stack<Integer>();
    st.push(-1024);
    st2.push(-1024);
    if (st.pop() == st2.peek()) {
        System.out.println("same");
    }

The above code should print "same" but fails to do as the if condition fails.

Stack<Integer> st = new Stack<Integer>();
    Stack<Integer> st2 = new Stack<Integer>();
    st.push(-1024);
    st2.push(-1024);
    int temp = st.pop();
    int temp2 = st2.peek();
    if (temp == temp2) {
        System.out.println("same");
    }

But when I store the pop and peek function values in a temporary variables then the if condition returns true. The problem seems to exist for pop and pop functions.

Things I have done to find my silly mistake(cause I know I make many):

  • Change the pushed value to different values. I have found that When I use any number above 127 or any number below -127 the if condition fails.

  • Store the pop and peek values in a temporary values that seems to solve the problem. But still doesn't explain the problem why the if condition fails.

Can someone help me out why this is happening like this. Am I missing something silly? Thanks in advance tho.

Aucun commentaire:

Enregistrer un commentaire