PriorityQueue 源码解析

前言

PriorityQueue是优先队列, 也就是说在队列中的元素是有优先级的, 优先级高的元素会先出队列.

本文源码: 本文源码下载

例子

先以一个简单的例子来了解一下PriorityQueue的简单用法.

package com.priorityqueue;

import java.util.Comparator;

public class Test01 {
    public static void main(String[] args) {
        PriorityQueue pq = new PriorityQueue<>(10, new Comparator() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        pq.add(1);
        pq.add(3);
        pq.add(2);
        pq.add(0);
        while (!pq.isEmpty()) {
            System.out.print(pq.poll() + " ");
        }
    }
}

输出如下: 可以看到输出结果并不是按加入的顺序输出,而是按照优先级大小输出的.

0 1 2 3

源码

属性

// 默认队列容量大小
    private static final int DEFAULT_INITIAL_CAPACITY = 11;

    /**
     * 存储元素用的数组
     */
    transient Object[] queue; // non-private to simplify nested class access

    /**
     * 当前队列中元素的个数
     */
    private int size = 0;

    /**
     * The comparator, or null if priority queue uses elements'
     * natural ordering.
     *
     * 比较器
     */
    private final Comparator comparator;

    /**
     * The number of times this priority queue has been
     * structurally modified.  See AbstractList for gory details.
     */
    transient int modCount = 0; // non-private to simplify nested class access

构造函数

    public PriorityQueue(int initialCapacity) {
        this(initialCapacity, null);
    }
    public PriorityQueue(Comparator comparator) {
        this(DEFAULT_INITIAL_CAPACITY, comparator);
    }
    public PriorityQueue(int initialCapacity,
                         Comparator comparator) {
        // Note: This restriction of at least one is not actually needed,
        // but continues for 1.5 compatibility
        if (initialCapacity < 1)
            throw new IllegalArgumentException();
        this.queue = new Object[initialCapacity];
        this.comparator = comparator;
    }

加入元素

/**
     * 将元素e加入到优先队列中
     * 以下情况下会报异常:
     * 1. e为null会抛出NullPointerException异常
     * 2. e无法比较会抛出ClassCastException异常
     * 3. 容量达到极限抛出OutofMemoryException异常
     *
     * @return {@code true} (as specified by {@link Collection#add})
     * @throws ClassCastException if the specified element cannot be
     *         compared with elements currently in this priority queue
     *         according to the priority queue's ordering
     * @throws NullPointerException if the specified element is null
     */
    public boolean add(E e) {
        return offer(e);
    }

    /**
     * 将元素e加入到优先队列中
     * 以下情况下会报异常:
     * 1. e为null会抛出NullPointerException异常
     * 2. e无法比较会抛出ClassCastException异常
     * 3. 容量达到极限抛出OutofMemoryException异常
     * @return {@code true} (as specified by {@link Queue#offer})
     * @throws ClassCastException if the specified element cannot be
     *         compared with elements currently in this priority queue
     *         according to the priority queue's ordering
     * @throws NullPointerException if the specified element is null
     */
    public boolean offer(E e) {
        if (e == null)
            throw new NullPointerException();
        modCount++;
        int i = size;
        if (i >= queue.length)
            grow(i + 1);
        size = i + 1;
        if (i == 0)
            queue[0] = e;
        else
            siftUp(i, e);
        return true;
    }

可以看到最终调用的是siftUp(i, e)方法, 接下来看看该方法是如何实现的.

    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 key = (Comparable) x;
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (key.compareTo((E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = key;
    }

    @SuppressWarnings("unchecked")
    private void siftUpUsingComparator(int k, E x) {
        while (k > 0) {
            int parent = (k - 1) >>> 1;
            Object e = queue[parent];
            if (comparator.compare(x, (E) e) >= 0)
                break;
            queue[k] = e;
            k = parent;
        }
        queue[k] = x;
    }

看着代码可能不那么好理解, 接下来以一个例子来辅助理解这段代码.

PriorityQueue 源码解析_第1张图片
图片.png

上图是一个优先队列,蓝色字代表该节点对应的数组下标, 对应的数组如下:


图片.png

可以看到堆是一个完全二叉树, 如果一个节点的下标是i, 则该节点的父亲节点下标是(i - 1) / 2, 根节点下标是0.

现在看看往堆中增加一个元素2是如何操作的.

PriorityQueue 源码解析_第2张图片
图片.png

最终用数组的表现形式如下:


图片.png

消费元素

@SuppressWarnings("unchecked")
    public E poll() {
        if (size == 0)
            return null;
        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;
    }

同样的道理该方法的重点还是在siftDown, 思路是取出下标为0的节点并且保存最后一个节点的元素, 相当于把最后一个节点放到下标为0的位置, 因为有可能此操作会导致堆的性质被破坏, 所以需要利用siftDown来维持堆的性质.

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 key = (Comparable)x;
        int half = size >>> 1;        // loop while a non-leaf
        while (k < half) {
            int child = (k << 1) + 1; // assume left child is least
            Object c = queue[child];
            int right = child + 1;
            if (right < size &&
                    ((Comparable) 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;
    }

    @SuppressWarnings("unchecked")
    private void siftDownUsingComparator(int k, E x) {
        int half = size >>> 1;
        while (k < half) {
            int child = (k << 1) + 1;
            Object c = queue[child];
            int right = child + 1;
            if (right < size &&
                    comparator.compare((E) c, (E) queue[right]) > 0)
                c = queue[child = right];
            if (comparator.compare(x, (E) c) <= 0)
                break;
            queue[k] = c;
            k = child;
        }
        queue[k] = x;
    }

相对于siftUp需要去找到parent, siftDown则需要去找到两个child, 如果当前节点的下标是i, 那此节点的左孩子节点下标为2 * i + 1, 右孩子下标为2 * i + 2.

以下也是通过一个小例子来解析该代码要做的事情.


PriorityQueue 源码解析_第3张图片
图片.png

对应的数组表示如下:


图片.png

删除元素

   /** 返回值:(遍历的时候会用到)
     * 如果往下调整 则返回null
     * 如果往上调整 则需要返回被调整的moved值
     *
     */
@SuppressWarnings("unchecked")
    private E removeAt(int i) {
        // assert i >= 0 && i < size;
        modCount++;
        int s = --size;
        if (s == i) // removed last element
            queue[i] = null;
        else {
            E moved = (E) queue[s];
            queue[s] = null;
            siftDown(i, moved);
            if (queue[i] == moved) {
                siftUp(i, moved);
                if (queue[i] != moved)
                    return moved;
            }
        }
        return null;
    }

可以看到该方法是删除在下标i的元素, 如果是最后一个元素可以直接删除而不会影响堆的性质, 如果不是则需要先模拟删除最后一个元素然后把该元素插入到i的位置, 因为此时不知道放到i这个位置是对堆的结构上面有影响还是下侧有影响, 因此就先通过往下调整来尝试, 如果往下调整成功则不需要往上调整, 否则需要继续往上调整.

遍历元素

遍历元素Iterator的本质作用就是遍历整个元素,在遍历的过程中可通过iterator.remove()来删除元素.

先通过一个例子来看看如何工作的.

package com.priorityqueue;

import java.util.Comparator;
import java.util.Iterator;

public class Test02 {
    public static void main(String[] args) {
        PriorityQueue pq = new PriorityQueue<>(10, new Comparator() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });
        pq.add(1);
        pq.add(3);
        pq.add(12);
        pq.add(4);
        pq.add(6);
        pq.add(17);
        pq.add(13);
        pq.add(8);
        pq.add(5);
        pq.add(10);
        pq.add(11);
        pq.add(19);
        pq.add(23);
        pq.add(14);

        System.out.println(pq);

        Iterator iter = pq.iterator();
        while (iter.hasNext()) {
            int val = iter.next();
            //if (val == 23) iter.remove();
            System.out.print(val + " ");
        }
    }
}

输出如下: 正常输出.

[1, 3, 12, 4, 6, 17, 13, 8, 5, 10, 11, 19, 23, 14]
1 3 12 4 6 17 13 8 5 10 11 19 23 14 

那如果在遍历过程中如果删除元素会怎么样呢?把上文代码中打开删除元素23. 可以得知在删除过程中需要调整整个堆的结构,也就疑问着原有结构会产生变化. 至于会产生什么变化, 看下图.

PriorityQueue 源码解析_第4张图片
图片.png

可以看到当Iterator遍历到23时, 然后删除23节点时, 会调整到右侧的图结构, 可以看到调整后14节点所在的位置也就被遍历过了, 14这个节点是如何被遍历的呢?

答案是在删除的过程中如果是需要向上调整时最后的一个元素(比如14)可能会被调整到一个被已经遍历过的位置(下标5), 但是会有一个ArrayDeque对象来加入到这个节点,等到正常顺序遍历完后会从ArrayDeque对象取元素. 当向下调整时就没有必要加入到ArrayDeque对象中,因为下面的元素都还没有被遍历过.

    public Iterator iterator() {
        return new Itr();
    }

    private final class Itr implements Iterator {
        /**
         * 当前遍历到元素下标
         */
        private int cursor = 0;

        /**
         * 上个被遍历的元素下标
         */
        private int lastRet = -1;

        /**
         * 存放因为删除元素而导致被替换到已经被遍历过的下标所在的位置上
         * 放到正常遍历结束后再取这里所有的元素
         */
        private ArrayDeque forgetMeNot = null;

        /**
         * 在遍历forgetMeNot时上个遍历元素
         */
        private E lastRetElt = null;

        /**
         * The modCount value that the iterator believes that the backing
         * Queue should have.  If this expectation is violated, the iterator
         * has detected concurrent modification.
         */
        private int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor < size ||
                    (forgetMeNot != null && !forgetMeNot.isEmpty());
        }

        @SuppressWarnings("unchecked")
        public E next() {
            if (expectedModCount != modCount)
                throw new ConcurrentModificationException();
            if (cursor < size) //正常遍历情况
                return (E) queue[lastRet = cursor++];
            if (forgetMeNot != null) { // 从forgetMeNot中取元素
                //System.out.println("in forgetMeNot != null next()");
                lastRet = -1;
                lastRetElt = forgetMeNot.poll();
                if (lastRetElt != null)
                    return lastRetElt;
            }
            throw new NoSuchElementException();
        }

        public void remove() {
            if (expectedModCount != modCount)
                throw new ConcurrentModificationException();
            if (lastRet != -1) { // 正常遍历过程中删除元素
                /**
                 * moved为null 表明是不会影响遍历情况
                 * 否则需要加入到ArrayDeque留作后续遍历 因为该元素被调整到之前已经被遍历的下标位置了
                 */
                E moved = PriorityQueue.this.removeAt(lastRet);
                lastRet = -1;
                if (moved == null)
                    cursor--;
                else {
                    if (forgetMeNot == null)
                        forgetMeNot = new ArrayDeque<>();
                    //System.out.println("forgetMeNot add moved:" + moved);
                    forgetMeNot.add(moved);
                }
            } else if (lastRetElt != null) { // 遍历ArrayDeque过程中删除元素
                PriorityQueue.this.removeEq(lastRetElt);
                lastRetElt = null;
            } else {
                throw new IllegalStateException();
            }
            expectedModCount = modCount;
        }
    }

扩容

因为PriorityQueue是被设计成无界的,所以当元素越来越多时需要进行扩大容量. 代码比较简单就不多说了.

参考

1. Java1.8 源码

你可能感兴趣的:(PriorityQueue 源码解析)