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() 不会抛出异常
堆构建过程图示:
这里写图片描述
堆构建过程中,需要添加的位置,与parent比较,如果parent的优先级较低,那么往下移动,待插入元素上浮(上浮名称的由来)。直到找到合适的位置。
数据构建过程图示:
这里写图片描述
可以看到,添加过程中的操作是上浮的过程。时间复杂度与其构建的堆深度有关,故其时间复杂度为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;
    }

删除重建堆过程:
这里写图片描述
最后一个元素放在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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值