Java Stack 類

棧是Vector的一個子類,它實現了一個標準的後進先出的棧。

堆疊只定義了默認構造函數,用來創建一個空棧。 堆疊除了包括由Vector定義的所有方法,也定義了自己的一些方法。

Stack()

除了由Vector定義的所有方法,自己也定義了一些方法:

序號 方法描述
1 boolean empty() 
測試堆疊是否為空。
2 Object peek( )
查看堆疊頂部的對象,但不從堆疊中移除它。
3 Object pop( )
移除堆疊頂部的對象,並作為此函數的值返回該對象。
4 Object push(Object element)
把項壓入堆疊頂部。
5 int search(Object element)
返回對象在堆疊中的位置,以 1 為基數。

實例

下麵的程式說明這個集合所支持的幾種方法

實例

import java.util.*; public class StackDemo { static void showpush(Stack<Integer> st, int a) { st.push(new Integer(a)); System.out.println("push(" + a + ")"); System.out.println("stack: " + st); } static void showpop(Stack<Integer> 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<Integer> st = new Stack<Integer>(); 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"); } } }

以上實例編譯運行結果如下:

stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack