Skip to content

Instantly share code, notes, and snippets.

@purplejacket
Last active October 24, 2018 15:53
Show Gist options
  • Save purplejacket/2648111 to your computer and use it in GitHub Desktop.
Save purplejacket/2648111 to your computer and use it in GitHub Desktop.
An implementation of a stack in java ... but with a bug in it
import java.util.*;
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 result = elements[--size];
return result;
}
/**
* 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);
}
}
public static void main(String[] args) {
Stack s = new Stack(0);
for (int i=0; i < args.length; i++)
s.push(args[i]);
for (int i=0; i < args.length; i++)
System.out.println(s.pop());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment