Still confused about the "==" for comparing the peek results.


  • 0
    G

    I was trying to implement the min stack using the two stack approach, and got stuck on the condition of (stack.peek()==minStack.peek()). I understand that the peek method returns an Integer Object, and therefore the equals method should work. What confuses me is that when I test the following codes locally on my computer, I get the output of "true":

    public static void main(String[] args){
        Stack<Integer> s1 = new Stack<Integer>();
        Stack<Integer> s2 = new Stack<Integer>();
        int x = 1;
        int y = 1;
        s1.push(x);
        s2.push(y);
        System.out.println(s1.peek()==s2.peek());
    }
    

    However if I write the program in the following way, I get the "false" output as expected:

    public static void main(String[] args){
    	Stack<Integer> s1 = new Stack<Integer>();
    	Stack<Integer> s2 = new Stack<Integer>();
    	Integer x = new Integer(1);
    	Integer y = new Integer(1);
    	s1.push(x);
    	s2.push(y);
    	System.out.println(s1.peek()==s2.peek());		
    }
    

    Can anyone help me understand the difference between the two programs?


  • 0
    G

    I think that is because the peek() function returns the object in the stack top instead of value of the top element in the lower case. If you add an (int) cast, the result should be true.
    In java Integer is a class while int is a primitive type.
    Although in eclipse I find this two no difference in these two cases.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.