Created
February 20, 2011 06:11
-
-
Save TonnyXu/835761 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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(); | |
return elements[--size]; | |
} | |
/** | |
* 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[] oldElements = elements; | |
elements = new Object[2 * elements.length + 1]; | |
System.arraycopy(oldElements, 0, elements, 0, size); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment