In Java, the Stack class represents a last-in-first-out (LIFO) object stack. The stack is a very common data structure that uses a typical first-in-last-out operation. Each stack contains a stack top. Each time the stack is popped, the data on the top of the stack is taken out, as follows:
Stack extends Vector with five operations, allowing vectors to be treated as stacks. The five operations are as follows:
# ## Description | empty() |
# Test whether the stack is empty. |
##peek() |
View the object at the top of the stack without removing it from the stack. |
##pop () |
Remove the object at the top of the stack and return it as the value of this function.
| ##push(E item)
|
| search(Object o)
|
|
public class Stack<E> extends Vector<E> Copy after login |
/** * 构造函数 */ public Stack() { } /** * push函数:将元素存入栈顶 */ public E push(E item) { // 将元素存入栈顶。 // addElement()的实现在Vector.java中 addElement(item); return item; } /** * pop函数:返回栈顶元素,并将其从栈中删除 */ public synchronized E pop() { E obj; int len = size(); obj = peek(); // 删除栈顶元素,removeElementAt()的实现在Vector.java中 removeElementAt(len - 1); return obj; } /** * peek函数:返回栈顶元素,不执行删除操作 */ public synchronized E peek() { int len = size(); if (len == 0) throw new EmptyStackException(); // 返回栈顶元素,elementAt()具体实现在Vector.java中 return elementAt(len - 1); } /** * 栈是否为空 */ public boolean empty() { return size() == 0; } /** * 查找“元素o”在栈中的位置:由栈底向栈顶方向数 */ public synchronized int search(Object o) { // 获取元素索引,elementAt()具体实现在Vector.java中 int i = lastIndexOf(o); if (i >= 0) { return size() - i; } return -1; }
The above is the content of Java Improvement (Sanyi)-----Stack. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!