Java泛型实现一个栈
在实现一个栈的时候,使用泛型有一下几个需要注意的点。
import java.util.Arrays; import java.util.EmptyStackException; public class MyStack<E> { private E[] element; private int size = 0; private static final int DEFAUL_INIT_CAPACITY = 16; @SuppressWarnings("unchecked") public MyStack() { element = (E[]) new Object[DEFAUL_INIT_CAPACITY]; } public void push(E e) { ensureCapacity(); element[size++] = e; } public E pop() { if (size == 0) throw new EmptyStackException(); E result = element[--size]; element[size] = null; return result; } public boolean isEmpty() { return size == 0; } private void ensureCapacity() { if (element.length == size) { element = Arrays.copyOf(element, 2 * size + 1); } } }