Something very wierd with JAVA compiler


#1

This gives WA for a test case on Submission -

public void pop() {
    if(!st.empty()){
        
     if(st.peek() == minSt.peek())
     minSt.pop();
     
     st.pop();
    
    }
}

Whereas this change makes it pass -

if(!st.empty()){
        int n = st.pop();
     if(n == minSt.peek())
     minSt.pop();

Does it make sense to anyone? Not sure peek before pop can cause any difference.


#2

Minor update -
The change from

 if(st.peek() == minSt.peek())
 minSt.pop();
 
 st.pop();

To -

 int n=st.peek();
 if(n== minSt.peek())
 minSt.pop();
 
 st.pop();

Makes it work. How can this be possible?


#3

yeah, i am facing the same problem…i dont know whats the difference between the two methods…??


#4

Same Issue here, Can’t figure out why


#5

apparently it has something to do with java.lang.Integer and a concept of auto boxing where in different objects are returned for same values and since = checks the objects and not value, it returns false. When storing in a separate int variable, this auto boxing is unboxed thereby returning same object for both values when equal , thereby returning true.
You can see more about this here. https://stackoverflow.com/questions/13098143/why-does-the-behavior-of-the-integer-constant-pool-change-at-127