import java.util.Arrays; public class AStack implements IStack { private Object[] entries; private int top; public AStack() { entries = new Object[10]; top = 0; } public void push(T newItem) { if(top >= entries.length) { //resize } entries[top] = newItem; top++; } @SuppressWarnings("unchecked") public T peek() { if(isEmpty()) { throw new EmptyStackException(); } return (T)entries[top - 1]; } @SuppressWarnings("unchecked") public T pop() { if(isEmpty()) { throw new EmptyStackException(); } T out = (T)entries[top - 1]; entries[top - 1] = null; //interest the garbage collector top--; return out; } public boolean isEmpty() { return top == 0; } public int size() { return top; } @Override public String toString() { if(isEmpty()) { return "[]"; } StringBuffer sb = new StringBuffer(); sb.append("["); for(int k = top - 1; k > 0; k--) { sb.append(String.format("%s, ", entries[k])); } sb.append(String.format("%s]", entries[0])); return sb.toString(); } private newSize(int n) { return n < 1000? 2*n : 3*n/2; } public static void main(String[] args) { IStack s = new AStack(); s.push("A"); s.push("B"); s.push("C"); System.out.println(s); System.out.println(s.size()); s.pop(); s.pop(); s.pop(); System.out.println(s); System.out.println(s.isEmpty()); } }