package algorithms;
import java.util.EmptyStackException;
public class Stack<T> {
private T[] elements;
private int top;
@SuppressWarnings("unchecked")
public Stack(int initCapacity){
elements = (T[])new Object[initCapacity];
}
public void push(T e){
ensureCapacity();
elements[top++] = e;
}
@SuppressWarnings("unchecked")
private void ensureCapacity(){
if(top == elements.length){
T[] oldElements = elements;
int newLen = (int) (elements.length * 0.1 + elements.length) + 1;//自动扩容10%;
elements = (T[])new Object[newLen];
System.arraycopy(oldElements, 0, elements, 0, oldElements.length);
}
}
public T pop(){
if(elements.length == 0)
throw new EmptyStackException();
T result = elements[--top];
elements[top] = null;
return result;
}
public static void main(String[] args){
Stack<Integer> stack = new Stack<Integer>(0);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
stack = null;
Stack<String> anotherStack = new Stack<String>(0);
anotherStack.push("I");
anotherStack.push("love");
anotherStack.push("you");
System.out.println(anotherStack.pop());
System.out.println(anotherStack.pop());
System.out.println(anotherStack.pop());
}
}
输出: