Created
October 28, 2015 22:09
-
-
Save michaellihs/8f91c7315b017bfa6ecc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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