Java 简明教程
Java Stack Class
Introduction
Stack 是 Vector 的一个子类,它实现了一个标准的后进先出栈。
Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Stack 只定义默认构造函数,它创建一个空栈。Stack 包含由 Vector 定义的所有方法,并添加了几个自己的方法。
Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.
Java Stack 类表示一个对象的后进先出 (LIFO) 栈。
The Java Stack class represents a last-in-first-out (LIFO) stack of objects.
-
When a stack is first created, it contains no items.
-
In this class, the last element inserted is accessed first.
Class declaration
以下是 java.util.Stack 类的声明:
Following is the declaration for java.util.Stack class −
public class Stack<E>
extends Vector<E>
Methods inherited
此类从以下类中继承方法:
This class inherits methods from the following classes −
-
java.util.Vector
-
java.util.Collection
-
java.util.Object
-
java.util.List
Example
以下程序说明了 Stack 集合支持的若干方法 -
The following program illustrates several of the methods supported by Stack collection −
import java.util.*;
public class StackDemo {
static void showpush(Stack st, int a) {
st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}
static void showpop(Stack st) {
System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}
public static void main(String args[]) {
Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}
这会产生以下结果 −
This will produce the following result −