1

While doing a leet code problem "Min Stack", I used push(int x) as a function definition, to push elements into an ArrayList.

The program works fine for input bigger or equal to -128 (or -2^8). But it bugs for numbers smaller than that.

  • changing push(int x) to push(Integer x) fixes the problem
  • but I don't I understand:
    • why int doesn't work, I assumed that java auto unboxes (int to Integer)
    • Why is it treating it as if it was a Byte ( -128 ??)

class MinStack {
    ArrayList<Integer> stack, mins;

    public MinStack() {
        stack = new ArrayList<>();
        mins = new ArrayList<>();

    }

    // change to Integer, works fine
    public void push(int x) {
        stack.add(x);
        if(mins.size() == 0 || mins.get(mins.size() - 1) >= x ){
           mins.add(x); 
        } 
    }

    public void pop() {

        if(stack.size() > 0){
            if(mins.size() > 0){
                if(stack.get(stack.size() - 1) == mins.get(mins.size() - 1)){
                    mins.remove(mins.size() - 1);
                }
            }
            stack.remove(stack.size() - 1);
        }



    }



    public int getMin() {
        return mins.get(mins.size() -  1);
    }
}

try: push(512), push(-128), push(-128), push(512), pop(), getMin(), pop(), getMin(), pop(), getMin()

output: -128 -128 512 works fine in both int and Integer version

try: push(512), push(-129), push(-129), push(512), pop(), getMin(), pop(), getMin(), pop(), getMin()

output: int version: -129 -129 -129 Integer version: -129 -129 512

Slei
  • 111
  • 8
  • 2
    Don't use == to compare objects. Use equals(). – JB Nizet Jul 03 '19 at 09:39
  • I don't understand, the version with Integer (Object) works fine. The version with primitives int, is the one that doesn't work. (java beginner with c++ background here, so sorry if I missing something obvious) – Slei Jul 03 '19 at 09:57
  • 1
    In both cases, you're comparing instances of Integer with ==. That tests if the two objects are identical, not if they have the same value. When using primitives, they're auto-boxed into Integer. Integer.valueOf(10) is the same object as Integer.valueOf(10). But Integer.valueOf(129) is not the same object as Integer.valueOf(129). When using Integers explicitely, I guess you always use `new Integer(10)`, always creating different objects. – JB Nizet Jul 03 '19 at 10:01
  • @Slei - _The version with primitives int_ is also _with Integer (Object)_ - `ArrayList stack, mins;`. – Armali Jul 03 '19 at 10:42
  • @JB Nizet now I get it, thanks. – Slei Jul 03 '19 at 12:27

0 Answers0