Date(10.3.2021)<對java的棧類的一些總結>
阿新 • • 發佈:2021-10-03
Java stack 類
棧是Vector的一個子類,它實現了一個標準的後進先出的棧。
堆疊只定義了預設建構函式,用來建立一個空棧。 堆疊除了包括由Vector定義的所有方法,也定義了自己的一些方法。
Stack()
序號 | 方法描述 |
---|---|
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