The following code compiles, but produces unexpected results (sub-optimal)

The following code compiles, but produces unexpected results (sub-optimal) even under

single-threaded conditions so not related to multi threading.

Need analysis of the problem.

import java.util.EmptyStackException;

public class Stack {
    private Object[] elements;
    private int size = 0;

    public Stack(int initialCapacity) {
        this.elements = new Object[initialCapacity];
    }

    public void push(Object e) {
        ensureCapacity();
        elements[size++] = e;
    }

    public Object pop() {
        if (size == 0)
            throw new EmptyStackException();
        Object pop = elements[--size];
        return pop;
    }

    /**
     * Ensure space for at least one more element, roughly
     * doubling the capacity each time the array needs to grow.
     */
    private void ensureCapacity() {
        if (elements.length == size) {
            Object[] newElements = new Object[2 * elements.length + 1];
            System.arraycopy(elements, 0, newElements, 0, size);
            elements = newElements;
        }
    }

}

I feel that the ensureCapacity function needs to check for overflow while doubling the capacity in case the stack is full.

Are there any other issues with the code?

Comments (0)