Latest web development tutorials

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 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");
      }
   }
}

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

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