标签:
源码版本为JDK1.7.0_75。
该类继承自Vector,说明该类是可克隆的、可序列化的,且是同步的。
public class Stack<E> extends Vector<E> |
构造函数
public Stack() { } |
入栈
/** * 将一个元素放入栈顶,通过vector类的addElement方法实现 * Pushes an item onto the top of this stack. This has exactly * the same effect as: * <blockquote><pre> * addElement(item)</pre></blockquote> * * @param item the item to be pushed onto this stack. * @return the <code>item</code> argument. * @see java.util.Vector#addElement */ public E push(E item) { addElement(item);
return item; } |
出栈
/** * 删除栈顶元素并将其返回,使用peek方法获取栈顶元素,使用vector类的removeElementAt方法完成元素的删除 * Removes the object at the top of this stack and returns that * object as the value of this function. * * @return The object at the top of this stack (the last item * of the <tt>Vector</tt> object). * @throws EmptyStackException if this stack is empty. */ public synchronized E pop() { E obj; int len = size();
obj = peek(); removeElementAt(len - 1);
return obj; } /** * 查看栈顶元素,但不将其从栈顶删除,使用vector类的elementAt方法实现。 * Looks at the object at the top of this stack without removing it * from the stack. * * @return the object at the top of this stack (the last item * of the <tt>Vector</tt> object). * @throws EmptyStackException if this stack is empty. */ public synchronized E peek() { int len = size();
if (len == 0) throw new EmptyStackException(); return elementAt(len - 1); } |
是否为空
/** * Tests if this stack is empty. * * @return <code>true</code> if and only if this stack contains * no items; <code>false</code> otherwise. */ public boolean empty() { return size() == 0; } |
搜索
/** * vector从n-1到0对应栈顶到栈底,因此在搜索时,应使用lastIndexOf方法 * Returns the 1-based position where an object is on this stack. * If the object <tt>o</tt> occurs as an item in this stack, this * method returns the distance from the top of the stack of the * occurrence nearest the top of the stack; the topmost item on the * stack is considered to be at distance <tt>1</tt>. The <tt>equals</tt> * method is used to compare <tt>o</tt> to the * items in this stack. * * @param o the desired object. * @return the 1-based position from the top of the stack where * the object is located; the return value <code>-1</code> * indicates that the object is not on the stack. */ public synchronized int search(Object o) { int i = lastIndexOf(o);
if (i >= 0) { return size() - i; } return -1; } |
标签:
原文地址:http://www.cnblogs.com/olivelv/p/5207629.html