java.util.Queue(隊列)的簡單使用


import java.util.LinkedList;
import java.util.Queue;

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

/**
 * 隊列測試:實現類使用LinkedList
 * 
 * Queue也有很多其他的實現類,比如java.util.concurrent.LinkedBlockingQueue。
 * LinkedBlockingQueue是一個阻塞的線程安全的隊列,底層實現也是使用鏈式結構。
 */
public class TestQuene {

    // 定義一個隊列
    Queue<String> queue;

    @Before
    public void before() {
        // 實例化隊列變量
        queue = new LinkedList<String>();

        // add方法向隊列中添加元素,返回布爾值,add方法添加失敗時會拋異常,不推薦使用
        // queue.add("1");
        // queue.add("2");
        // queue.add("3");
        // queue.add("4");
        // queue.add("5");

        // offer方法向隊列中添加元素,返回布爾值
        queue.offer("a");
        queue.offer("b");
        queue.offer("c");
        queue.offer("d");
        queue.offer("e");

    }

    // poll方法移除隊列首個元素並返回,若隊列為空,返回null
    @Test
    public void test1() {
        // 彈出元素
        String pollEle = queue.poll(); // 先進先出,彈出了a
        System.out.println(pollEle); // a
        System.out.println(queue); // [b, c, d, e]
    }

    // remove方法移除首個元素並返回,若隊列為空,會拋出異常:NoSuchElementException,不推薦使用
    @Test
    public void test2() {
        // 彈出元素
        String remove = queue.remove(); // 先進先出,彈出了a
        System.out.println(remove); // a
        System.out.println(queue); // [b, c, d, e]
    }

    // peek方法返回隊列首個元素,但不移除,若隊列為空,返回null
    @Test
    public void test3() {
        // 查看首個元素
        String peek = queue.peek(); // 首個元素是a,最先加入
        System.out.println(peek); // a
        System.out.println(queue); // [a, b, c, d, e]
    }

    // element方法返回隊列的頭元素,但不移除,若隊列為空,會拋出異常:NoSuchElementException,不推薦使用
    @Test
    public void test4() {
        // 查看首個元素
        String element = queue.element();
        System.out.println(element); // a
        System.out.println(queue); // [a, b, c, d, e]
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM