天天看點

Java容器 PriorityQueue源碼解析

PriorityQueue是基于堆的無界優先隊列實作。堆的子節點都不大于(最小堆)或都不小于(最大堆)的一種近似完全二叉樹的資料結構。

堆用數組實作,用數組的index作為索引。且 i 的父節點為 [i/2],子節點為[2i], [2i + 1],從數組的index=1開始計算(ProrityQueue中是從index=0開始存儲的)。

PriorityQueue 基本結構

public class PriorityQueue<E> extends AbstractQueue<E>
    implements java.io.Serializable {
        ...
        //基于數組的實作
        transient Object[] queue;
        //隊列中實際大小
        private int size = 0;
        //比較器,可以指定,沒有指定使用自然順序
        private final Comparator<? super E> comparator;

        ...
    }           

add() && offer()

//add本質是offer()的實作
    public boolean add(E e) {
        return offer(e);
    }

    public boolean offer(E e) {
        //不可添加null元素
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        // size > capcatiry時需要擴容
        if (i >= queue.length)
            grow(i + 1);

        size = i + 1;
        if (i == 0)
            queue[0] = e;
        else
            //基于堆的實作,添加元素上浮調整堆結構
            siftUp(i, e);
        return true;
    }

     private void siftUp(int k, E x) {
        //如果comparator不為null,使用指定的比較器的順序。如果comparator為null,使用自然順序。本質上隻有比較的方法不一樣,上浮操作還是一樣的
        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) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            // 當parent元素比添加的元素大,元素下沉
            if (key.compareTo((E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        //将元素放在合适的位置
        queue[k] = key;
    }           

在無界的過程中,add() & offer() 不會抛出異常

堆建構過程圖示:

Java容器 PriorityQueue源碼解析

堆建構過程中,需要添加的位置,與parent比較,如果parent的優先級較低,那麼往下移動,待插入元素上浮(上浮名稱的由來)。直到找到合适的位置。

資料建構過程圖示:

Java容器 PriorityQueue源碼解析

可以看到,添加過程中的操作是上浮的過程。時間複雜度與其建構的堆深度有關,故其時間複雜度為O(logN)

grow() 擴容

private void grow(int minCapacity) {
        int oldCapacity = queue.length;
        // 資料比較小就擴大到2倍,否則增大50%
        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);
    }           

remove() && poll()

@SuppressWarnings("unchecked")
    public E poll() {
        if (size == 0)
            return null;
        int s = --size;
        modCount++;
        //删除并傳回的是index=0的位置
        E result = (E) queue[0];
        //删除完之後重建堆,下沉
        E x = (E) queue[s];
        queue[s] = null;
        if (s != 0)
            siftDown(0, x);
        return result;
    }
    // 根據是否有comparator來排序
    private void siftDown(int k, E x) {
        if (comparator != null)
            siftDownUsingComparator(k, x);
        else
            siftDownComparable(k, x);
   }

    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) {
            // 将較大的孩子往上移,直到找到合适的位置k
            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;
    }           

删除重建堆過程:

Java容器 PriorityQueue源碼解析

最後一個元素放在index=0。較小的元素上浮到parent, 直到到葉子節點或者合适的位置.

element() && peek()

public E peek() {
      //就是這麼簡單粗暴啊~
        return (size == 0) ? null : (E) queue[0];
    }           

remove(Object obj)

remove(Object obj)需要先找到obj所在的位置。然後removeAt()。删除的過程與remove()類似。查詢對應的index的過程:

private int indexOf(Object o) {
        if (o != null) {
            // 循環數組
            for (int i = 0; i < size; i++)
                if (o.equals(queue[i]))
                    return i;
        }
        return -1;
    }           

PriorityQueue總結

PriorityQueue的順序可以根據指定的Comparator或者自然順序實作,元素需要實作Comparator,否者會有Cast Exception。

PriorityQueue中添加的元素不可為null。

PriorityQueue中的方法沒有實作同步。

offer && poll && remove && add 時間複雜度O(logN)

remove(Object obj) && contains(Object obj) 時間複雜度為O(N)

peek && element && size 時間複雜度O(1)

繼續閱讀