import java.util.Arrays; import java.util.Iterator; 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) { resizeArray(); } 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 void clear() { for(int k = 0; k < top; k++) { entries[k] = null; } top = 0; } public boolean isEmpty() { return top == 0; } public int size() { return top; } public Iterator iterator() { return new Navigator(); } class Navigator implements Iterator { private int nav; public Navigator() { nav = top; } public void remove() { throw new UnsupportedOperationException(); } public boolean hasNext() { return nav > 0; } @SuppressWarnings("unchecked") public T next() { T out = (T)entries[nav - 1]; nav--; return out; } } @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 int newSize(int n) { return n < 1000? 2*n : 3*n/2; } private void resizeArray() { int n = entries.length; int newLength = newSize(n); entries = Arrays.copyOf(entries, newLength); } 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());*/ IStack s = new AStack<>(); for(int k = 0; k < 10; k++) { s.push("" + k); } System.out.println(s.size()); System.out.println("********************"); for(String k : s) { System.out.println(k); } for(int k = 0; k < 10; k++) { s.pop(); } System.out.println(s.isEmpty()); } }