#16 Errors in a Stack Implementation
Describe all problems in the code:
public class Stack {
private Object[] elements;
private int size = 0;
private static final int DEFAULT_INITIAL_CAPACITY = 16;
public Stack() {
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public void push(Object e) {
ensureCapacity();
elements[size++] = e;
}
public Object pop() {
if (size == 0)
throw new EmptyStackException();
size-=1;
Object some = elements[size];
elemens[size] = null;
return some;
}
/** 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)
elements = Arrays.copyOf(elements, 2 * size + 1);
}
}
Question review
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor