A
A
Alina Mitrokhina2019-12-09 19:11:41
htaccess
Alina Mitrokhina, 2019-12-09 19:11:41

What problems are present in this code and how to improve it?

public class Stack {
    private final Object[] buf;
    private int position;

    public Stack(int size) {
        buf = new Object[size];
    }

    public void push(Object o) {
        if(position > buf.length - 1)
            throw new OutOfMemoryError();
        buf[position++] = o;
    }

    public Object pop() {
        if(position <= 0)
            return null;
        return buf[--position];
    }

    public boolean isEmpty() {
        return (position == 0);
    }

    public boolean equals(Stack stack) {
        return (buf == stack.buf);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Viktor Taran, 2019-01-11
@shambler81

Throw off the excel file it was,
well, yes, 1000 is not so much you can write down;)

T
tsarevfs, 2019-12-09
@tsarevfs

Most likely a bug:
buf == stack.bufwill only return true when it's the same array, not 2 arrays with equal elements. Use Arrays.equals(array1, array2). https://stackoverflow.com/a/8777279/1762922
Nibbling: It's
not clear how the position can become less than 0: if(position <= 0), it seems that an equality check is enough.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question