1. 程式人生 > 實用技巧 >集合-PriorityQueue 原始碼解析

集合-PriorityQueue 原始碼解析

問題

(1)什麼是優先順序佇列?

(2)怎麼實現一個優先順序佇列?

(3)PriorityQueue是執行緒安全的嗎?

(4)PriorityQueue就有序的嗎?

簡介

優先順序佇列,是0個或多個元素的集合,集合中的每個元素都有一個權重值,每次出隊都彈出優先順序最大或最小的元素。

一般來說,優先順序佇列使用堆來實現。

那麼Java裡面是如何通過“堆”這個資料結構來實現優先順序佇列的呢?

讓我們一起來學習吧。

原始碼分析

主要屬性

// 預設容量
private static final int DEFAULT_INITIAL_CAPACITY = 11;
// 儲存元素的地方
transient Object[] queue; // non-private to simplify nested class access // 元素個數 private int size = 0; // 比較器 private final Comparator<? super E> comparator; // 修改次數 transient int modCount = 0; // non-private to simplify nested class access

(1)預設容量是11;

(2)queue,元素儲存在陣列中,這跟我們之前說的堆一般使用陣列來儲存是一致的;

(3)comparator,比較器,在優先順序佇列中,也有兩種方式比較元素,一種是元素的自然順序,一種是通過比較器來比較;

(4)modCount,修改次數,有這個屬性表示PriorityQueue也是fast-fail的;

入隊

入隊有兩個方法,add(E e)和offer(E e),兩者是一致的,add(E e)也是呼叫的offer(E e)。

public boolean add(E e) {
    return offer(e);
}

public boolean offer(E e) {
    // 不支援null元素
    if (e == null)
        throw new NullPointerException();
    modCount++;
    // 取size
    int
i = size; // 元素個數達到最大容量了,擴容 if (i >= queue.length) grow(i + 1); // 元素個數加1 size = i + 1; // 如果還沒有元素 // 直接插入到陣列第一個位置 // 這裡跟我們之前講堆不一樣了 // java裡面是從0開始的 // 我們說的堆是從1開始的 if (i == 0) queue[0] = e; else // 否則,插入元素到陣列size的位置,也就是最後一個元素的下一位 // 注意這裡的size不是陣列大小,而是元素個數 // 然後,再做自下而上的堆化 siftUp(i, e); return true; } private void siftUp(int k, E x) { // 根據是否有比較器,使用不同的方法 if (comparator != null) siftUpUsingComparator(k, x); else siftUpComparable(k, x); } @SuppressWarnings("unchecked") private void siftUpComparable(int k, E x) { Comparable<? super E> key = (Comparable<? super E>) x; while (k > 0) { // 找到父節點的位置 // 因為元素是從0開始的,所以減1之後再除以2 int parent = (k - 1) >>> 1; // 父節點的值 Object e = queue[parent]; // 比較插入的元素與父節點的值 // 如果比父節點大,則跳出迴圈 // 否則交換位置 if (key.compareTo((E) e) >= 0) break; // 與父節點交換位置 queue[k] = e; // 現在插入的元素位置移到了父節點的位置 // 繼續與父節點再比較 k = parent; } // 最後找到應該插入的位置,放入元素 queue[k] = key; }

(1)入隊不允許null元素;

(2)如果陣列不夠用了,先擴容;

(3)如果還沒有元素,就插入下標0的位置;

(4)如果有元素了,就插入到最後一個元素往後的一個位置(實際並沒有插入哈);

(5)自下而上堆化,一直往上跟父節點比較;

(6)如果比父節點小,就與父節點交換位置,直到出現比父節點大為止;

(7)由此可見,PriorityQueue是一個小頂堆。

擴容

private void grow(int minCapacity) {
    // 舊容量
    int oldCapacity = queue.length;
    // Double size if small; else grow by 50%
    // 舊容量小於64時,容量翻倍
    // 舊容量大於等於64,容量只增加舊容量的一半
    int newCapacity = oldCapacity + ((oldCapacity < 64) ?
                                     (oldCapacity + 2) :
                                     (oldCapacity >> 1));
    // overflow-conscious code
    // 檢查是否溢位
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
        
    // 創建出一個新容量大小的新陣列並把舊陣列元素拷貝過去
    queue = Arrays.copyOf(queue, newCapacity);
}

private static int hugeCapacity(int minCapacity) {
    if (minCapacity < 0) // overflow
        throw new OutOfMemoryError();
    return (minCapacity > MAX_ARRAY_SIZE) ?
        Integer.MAX_VALUE :
        MAX_ARRAY_SIZE;
}

(1)當陣列比較小(小於64)的時候每次擴容容量翻倍;

(2)當陣列比較大的時候每次擴容只增加一半的容量;

出隊

出隊有兩個方法,remove()和poll(),remove()也是呼叫的poll(),只是沒有元素的時候丟擲異常。

public E remove() {
    // 呼叫poll彈出隊首元素
    E x = poll();
    if (x != null)
        // 有元素就返回彈出的元素
        return x;
    else
        // 沒有元素就丟擲異常
        throw new NoSuchElementException();
}

@SuppressWarnings("unchecked")
public E poll() {
    // 如果size為0,說明沒有元素
    if (size == 0)
        return null;
    // 彈出元素,元素個數減1
    int s = --size;
    modCount++;
    // 佇列首元素
    E result = (E) queue[0];
    // 佇列末元素
    E x = (E) queue[s];
    // 將佇列末元素刪除
    queue[s] = null;
    // 如果彈出元素後還有元素
    if (s != 0)
        // 將佇列末元素移到佇列首
        // 再做自上而下的堆化
        siftDown(0, x);
    // 返回彈出的元素
    return result;
}

private void siftDown(int k, E x) {
    // 根據是否有比較器,選擇不同的方法
    if (comparator != null)
        siftDownUsingComparator(k, x);
    else
        siftDownComparable(k, x);
}

@SuppressWarnings("unchecked")
private void siftDownComparable(int k, E x) {
    Comparable<? super E> key = (Comparable<? super E>)x;
    // 只需要比較一半就行了,因為葉子節點佔了一半的元素
    int half = size >>> 1;        // loop while a non-leaf
    while (k < half) {
        // 尋找子節點的位置,這裡加1是因為元素從0號位置開始
        int child = (k << 1) + 1; // assume left child is least
        // 左子節點的值
        Object c = queue[child];
        // 右子節點的位置
        int right = child + 1;
        if (right < size &&
            ((Comparable<? super E>) c).compareTo((E) queue[right]) > 0)
            // 左右節點取其小者
            c = queue[child = right];
        // 如果比子節點都小,則結束
        if (key.compareTo((E) c) <= 0)
            break;
        // 如果比最小的子節點大,則交換位置
        queue[k] = c;
        // 指標移到最小子節點的位置繼續往下比較
        k = child;
    }
    // 找到正確的位置,放入元素
    queue[k] = key;
}

(1)將佇列首元素彈出;

(2)將佇列末元素移到佇列首;

(3)自上而下堆化,一直往下與最小的子節點比較;

(4)如果比最小的子節點大,就交換位置,再繼續與最小的子節點比較;

(5)如果比最小的子節點小,就不用交換位置了,堆化結束;

(6)這就是堆中的刪除堆頂元素;

取隊首元素

取隊首元素有兩個方法,element()和peek(),element()也是呼叫的peek(),只是沒取到元素時丟擲異常。

public E element() {
    E x = peek();
    if (x != null)
        return x;
    else
        throw new NoSuchElementException();
}
public E peek() {
    return (size == 0) ? null : (E) queue[0];
}

(1)如果有元素就取下標0的元素;

(3)如果沒有元素就返回null,element()丟擲異常;

總結

(1)PriorityQueue是一個小頂堆;

(2)PriorityQueue是非執行緒安全的;

(3)PriorityQueue不是有序的,只有堆頂儲存著最小的元素;

(4)入隊就是堆的插入元素的實現;

(5)出隊就是堆的刪除元素的實現;

彩蛋

(1)論Queue中的那些方法?

Queue是所有佇列的頂級介面,它裡面定義了一批方法,它們有什麼區別呢?

操作丟擲異常返回特定值
入隊 add(e) offer(e)——false
出隊 remove() poll()——null
檢查 element() peek()——null

(2)為什麼PriorityQueue中的add(e)方法沒有做異常檢查呢?

因為PriorityQueue是無限增長的佇列,元素不夠用了會擴容,所以新增元素不會失敗。