java.util.Stack(棧)的簡單使用

import java.util.Stack;

import org.junit.Before;
import org.junit.Test;

/**
 * Stack(棧)繼承了Vector類,底層實現是數組。 
 * 此處只介紹了Stack本身定義的方法,父類中的方法再也不一一介紹。
 */
public class TestStack {

    // 定義一個棧
    Stack<String> stack;

    @Before
    public void before() {
        // 實例化棧變量
        stack = new Stack<String>();

        // add方法向棧中添加元素,添加成功返回true
        stack.add("1");
        stack.add("2");
        stack.add("3");
        stack.add("4");
        stack.add("5");

        // push方法向棧中添加元素,返回結果是當前添加的元素
        stack.push("a");
        stack.push("b");
        stack.push("c");
        stack.push("d");
        stack.push("e");

        // push和add都是向棧中添加元素,底層實現也是同樣的,都是先將Vector擴容,再添加

    }

    // pop方法移除並返回棧頂元素,若是是空棧,會拋出異常:EmptyStackException
    @Test
    public void test1() {
        String pop = stack.pop();
        System.out.println(pop); // e
        System.out.println(stack); // [1, 2, 3, 4, 5, a, b, c, d]
    }

    // peek方法獲取棧頂元素,但並不移除,若是是空棧,會拋出異常:EmptyStackException
    @Test
    public void test2() {
        String peek = stack.peek();
        System.out.println(peek); // e
        System.out.println(stack); // [1, 2, 3, 4, 5, a, b, c, d, e]
    }

    // empty方法檢查棧是不是空棧
    @Test
    public void test3() {
        boolean isEmpty = stack.empty();
        System.out.println(isEmpty); // false
    }

    // search方法查看某元素在棧中的位置,計數從1開始
    @Test
    public void test4() {
        int index = stack.search("1");
        System.out.println(index); // 10
    }

}
相關文章
相關標籤/搜索