Skip to content

Instantly share code, notes, and snippets.

@michaellihs
Created October 28, 2015 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaellihs/8f91c7315b017bfa6ecc to your computer and use it in GitHub Desktop.
Save michaellihs/8f91c7315b017bfa6ecc to your computer and use it in GitHub Desktop.
package ch.lihsmi.collections;
import java.util.Arrays;
final public class ArrayStack<T> implements Stack<T> {
private T[] elements;
private int position = 0;
private static final int DEFAULT_CAPACITY = 16;
@SuppressWarnings("unchecked")
public ArrayStack() {
this.elements = (T[]) new Object[DEFAULT_CAPACITY];
}
@Override
public void pop() throws EmptyStackException {
throwIfEmpty();
elements[position--] = null;
}
@Override
public T top() throws EmptyStackException {
throwIfEmpty();
return elements[position - 1];
}
@Override
public T topAndPop() throws EmptyStackException {
T element = top();
pop();
return element;
}
@Override
public void push(T element) {
ensureCapacity();
elements[position++] = element;
}
@Override
public boolean isEmpty() {
return position == 0;
}
private void throwIfEmpty() throws EmptyStackException {
if (position == 0) {
throw new EmptyStackException();
}
}
private void ensureCapacity() {
if (elements.length == position) {
elements = Arrays.copyOf(elements, 2 * position + 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment