1 public class MyStack<AnyType> { 2 private AnyType [] theItems; 3 private final int DEFAULT_CAPACITY = 100; 4 private int top; 5 6 7 public MyStack(){ //构造函数,生成空表 8 clear(); 9 } 10 11 public void clear(){ //归为默认(清空) 12 top = 0; 13 ensureCapacity(DEFAULT_CAPACITY); 14 } 15 16 public void ensureCapacity(int newCapacity ){ //重置表的容量 17 AnyType [] oldItems = theItems; 18 theItems = (AnyType []) new Object[newCapacity];//****重新分配空间 注意使用强制转换的方式进行定义 19 for (int i = 0 ; i < top; i++){ 20 theItems[i] = oldItems[i]; 21 } 22 } 23 24 public boolean isEmpty(){ //判断是否为空 25 return top == 0; 26 } 27 28 public boolean push( AnyType newVal){//末尾添加元素 29 if(theItems.length == top) 30 ensureCapacity(top * 2 + 1); 31 theItems[top++] = newVal; 32 return true; 33 } 34 35 public AnyType pop(){ 36 if(top == 0) 37 throw new NoSuchElementException(); 38 return theItems[--top]; 39 } 40 }