/**
* The <code>Stack</code> class represents a last-in-first-out
* (LIFO) stack of objects. It extends class <tt>Vector</tt> with five
* operations that allow a vector to be treated as a stack. The usual
* <tt>push</tt> and <tt>pop</tt> operations are provided, as well as a
* method to <tt>peek</tt> at the top item on the stack, a method to test
* for whether the stack is <tt>empty</tt>, and a method to <tt>search</tt>
* the stack for an item and discover how far it is from the top.
* <p>
* When a stack is first created, it contains no items.
*
* <p>A more complete and consistent set of LIFO stack operations is
* provided by the {@link Deque} interface and its implementations, which
* should be used in preference to this class. For example:
* <pre> {@code
* Deque<Integer> stack = new ArrayDeque<Integer>();}</pre>
*
* @author Jonathan Payne
* @since JDK1.0
*/
翻译如下:
栈是一个后进先出的数据结构,它是vector的子类,并且只有五种操作。分别是push,pop,peek,还有一个返回stack是否为空的方法:empty,最后一个方法是search,此方法是用于查询元素并且返回一个整型数代表此元素距离栈顶的距离。
/**
* Creates an empty Stack.
*/
public Stack() {
}
注解:只有一个构造函数,创建空栈
public E push(E item) {
addElement(item);
return item;
}
注解:元素进栈,使用的vector类的addElement方法,并且返回进栈元素
public synchronized E pop() {
E obj;
int len = size();
obj = peek();
removeElementAt(len - 1);
return obj;
}
注解:移除栈顶元素,首先使用的peek方法,获取栈顶元素值,然后使用的vector类的removeElementAt方法删除栈顶值。最后返回栈顶值(需要注意的是此方法是安全的)
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}
注解:返回栈顶元素。首先判断是否有元素存在,如果不存在即抛出空栈异常,否则直接调用父类的elementAt方法,返回栈顶元素。(这个方法也是同步安全的)
public boolean empty() {
return size() == 0;
}
注解:检查此栈是否为空
public synchronized int search(Object o) {
int i = lastIndexOf(o);
if (i >= 0) {
return size() - i;
}
return -1;
}
注解:返回参数距离栈顶的距离。首先是用父类的lastIndexOf方法,获取参数最后一次出现的位置,然后用栈的大小减去这个位置即可,如果元素不存在,则返回-1。(同步方法)