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