Java Collection之Queue詳解及用途

Queue是一種常見的數據結構,其主要特徵在於FIFO(先進先出),Java中的Queue是這樣定義的:

public interface Queue<E> extends Collection<E> {
    E element();
    boolean offer(E o);
    E peek();
    E poll();
    E remove();
}


雖然Queue都具有FIFO的特點,但具體輸出哪一個元素,Queue的各種實現是不同的,尤其是在排序的情況下,新輸入的元素並非放入隊列尾部,而是放在適當的位置。Queue的每一種實現都必須指定排序屬性(ordering properties)。

Queue可能對存放的元素數目有所限制。這樣的Queue成爲“有界的”(bounded),在Java.util.concurrent中的某些Queue實現是有界的,而java.util中的Queue實現不是有界的。

Queue的每個操作都有兩種方法:


Queue Interface Structure
  Throws exception Returns special value
Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()



add方法繼承自Collection,當Queue的元素已經到達限制數目時,add會拋出一個IllegalStateException異常;offer方法僅僅定位於應用在有界Queue的情況下,當Queue已經裝滿時,offer會返回false。

remove和poll方法都刪除並返回Queue中的頭元素(注意,並不是插入的第一個元素,因爲有的Queue實現是排序的)。當Queue爲空時,remove拋出NoSuchElementException異常,而poll返回null。

element和peek返回但不刪除Queue中的頭元素,它們的區別類似remove與poll。

Queue的實現一般並不容許插入null,只有LinkedList是一個意外,它容許插入null,但使用者必須注意,不要與poll和peek方法返回的null值混淆。

Queue的實現一般並不定義基於元素的equals和hashCode方法,而是調用繼承自Object的對應方法。

Queue接口並沒有定義並行程序中常用的阻塞方法,也就是說,元素進入Queue之前不必檢查Queue中是否有足夠的空間,不過作爲Queue擴展的java.util.concurrent.BlockingQueue接口定義了這些方法。

普通的LinkedList實現並沒有定義特殊的排序算法,所以輸出元素時會按照插入的順序:

import java.util.*;
public class Countdown {
    public static void main(String[] args)
            throws InterruptedException {
        int time = 10;
        Queue<Integer> queue = new LinkedList<Integer>();
        for (int i = time; i >= 0; i--)
            queue.add(i);
        while(!queue.isEmpty()) {
            System.out.println(queue.remove());
            Thread.sleep(1000);
        }
    }
}


程序的輸出結果爲:
10
9
8
…..

如果作一點小更改,採用PriorityQueue

import java.util.*;
public class Countdown {
    public static void main(String[] args)
            throws InterruptedException {
        int time = 10;
        Queue<Integer> queue = new LinkedList<Integer>();
        Queue<Integer> pQueue = new PriorityQueue<Integer>();
        for (int i = time; i >= 0; i--)
            queue.add(i);
        while(!queue.isEmpty()) {
            pQueue.add(queue.remove());           
        }
        while(!pQueue.isEmpty()) {
            System.out.println(pQueue.remove());           
        }
    }
}


則輸出結果爲:
0
1
2
……

查閱文檔可知,PriorityQueue的內部是一個min heap,實際上,觀察PriorityQueue的輸出也可以發現這一點:

        int time = 10;
        Queue<Integer> queue = new LinkedList<Integer>();
        Queue<Integer> pQueue = new PriorityQueue<Integer>();
        for (int i = time; i >= 0; i--)
            queue.add(i);
        while(!queue.isEmpty()) {
            pQueue.add(queue.remove());           
        }

        System.out.println(pQueue);
        pQueue.remove();
        System.out.println(pQueue);

輸出結果爲
[0,1,5,4,2,9,6,10,7,8,3]
[1,2,5,4,3,9,6,10,7,8]

實際上就是兩個min-heap按照從上至下,從左至右的輸出。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章