• PriorityQueue 源码解析(JDK1.8)


    目录

    一. 前言

    二. 源码解析

    2.1. 入队

    2.2. 出队

    2.3. 查找

    2.4. 基于集合构造优先队列


    一. 前言

        PriorityQueue,即优先队列。优先队列的作用是能保证每次取出的元素都是队列中权值最小的(Java的优先队列每次取最小元素,C++的优先队列每次取最大元素)。这里牵涉到了大小关系,元素大小的评判可以通过元素本身的自然顺序(natural ordering),也可以通过构造时传入的比较器(Comparator,类似于C++的仿函数)。

        Java中PriorityQueue实现了Queue接口,不允许放入null元素;其通过堆实现,具体说是通过完全二叉树(complete binary tree)实现的小顶堆(任意一个非叶子节点的权值,都不大于其左右子节点的权值),也就意味着可以通过数组来作为PriorityQueue的底层实现。

    上图中我们给每个元素按照层序遍历的方式进行了编号,如果你足够细心,会发现父节点和子节点的编号是有联系的,更确切的说父子节点的编号之间有如下关系:
    leftNo = parentNo*2+1
    rightNo = parentNo*2+2
    parentNo = (nodeNo-1)/2

    通过上述三个公式,可以轻易计算出某个节点的父节点以及子节点的下标。这也就是为什么可以直接用数组来存储堆的原因。

    PriorityQueue的peek()和element()操作是常数时间,add()、offer()、无参数的remove()以及poll()方法的时间复杂度都是log(N)。

    二. 源码解析

    2.1. 入队

    add(E e)offer(E e) 的语义相同,都是向优先队列中插入元素,只是Queue接口规定二者对插入失败时的处理不同,前者在插入失败时抛出异常,后者则会返回false。对于PriorityQueue这两个方法其实没什么差别。

    1. public boolean add(E e) {
    2. return offer(e);
    3. }
    4. public boolean offer(E e) {
    5. // 若添加的元素为null,则直接抛出空指针异常
    6. if (e == null)
    7. throw new NullPointerException();
    8. // 操作数+1
    9. modCount++;
    10. int i = size;
    11. // 如果元素个数已大于或等于数组的长度,则执行扩容操作
    12. if (i >= queue.length)
    13. grow(i + 1);
    14. // 将待添加元素添加到数组最后,并执行元素上移过程
    15. siftUp(i, e);
    16. // 元素添加完成后,元素个数+1
    17. size = i + 1;
    18. // 返回true,代表添加元素成功
    19. return true;
    20. }

    扩容函数:

    1. private void grow(int minCapacity) {
    2. // 获取现有容量
    3. int oldCapacity = queue.length;
    4. // Double size if small; else grow by 50%
    5. // 若现有容量<64,则新容量变为现有容量的2倍+2
    6. // 若现有容量>64,则新容量变为现有容量的1.5倍
    7. int newCapacity = oldCapacity + ((oldCapacity < 64) ?
    8. (oldCapacity + 2) :
    9. (oldCapacity >> 1));
    10. // overflow-conscious code
    11. // 若新容量大于Integer.MAX_VALUE - 8,执行hugeCapacity方法
    12. if (newCapacity - MAX_ARRAY_SIZE > 0)
    13. newCapacity = hugeCapacity(minCapacity);
    14. // 将老数组元素拷贝到新数组中
    15. queue = Arrays.copyOf(queue, newCapacity);
    16. }
    17. private static int hugeCapacity(int minCapacity) {
    18. if (minCapacity < 0) // overflow
    19. throw new OutOfMemoryError();
    20. return (minCapacity > MAX_ARRAY_SIZE) ?
    21. Integer.MAX_VALUE :
    22. MAX_ARRAY_SIZE;
    23. }

    元素上移:

    1. private void siftUp(int k, E x) {
    2. // 判断是否有传入的comparator
    3. // 若有则执行siftUpUsingComparator,否则执行siftUpComparable
    4. if (comparator != null)
    5. siftUpUsingComparator(k, x);
    6. else
    7. siftUpComparable(k, x);
    8. }
    9. private void siftUpComparable(int k, E x) {
    10. Comparablesuper E> key = (Comparablesuper E>) x;
    11. while (k > 0) {
    12. // 获取父节点的index=(k-1)/2
    13. int parent = (k - 1) >>> 1;
    14. // 拿到父节点的value
    15. Object e = queue[parent];
    16. // 若当前节点value>=父节点,停止上移,直接break返回
    17. if (key.compareTo((E) e) >= 0)
    18. break;
    19. // 若当前节点value>=父节点,与父节点替换,元素上移
    20. queue[k] = e;
    21. k = parent;
    22. }
    23. queue[k] = key;
    24. }
    25. // 过程基本与siftUpComparable相同,区别就是在元素上移的过程中,siftUpUsingComparator方法使用传入的Comparator来进行大小比较
    26. private void siftUpUsingComparator(int k, E x) {
    27. while (k > 0) {
    28. int parent = (k - 1) >>> 1;
    29. Object e = queue[parent];
    30. if (comparator.compare(x, (E) e) >= 0)
    31. break;
    32. queue[k] = e;
    33. k = parent;
    34. }
    35. queue[k] = x;
    36. }

    可以发现,PriorityQueue构造时若不传入自定义的Comparator,元素上移过程中进行Value比较的时候,默认使用的元素的compareTo方法。故PriorityQueue默认是最小优先队列,若需要最大优先队列,则需要传入相应的Comparator。

    2.2. 出队

    remove(Object o)poll() 方法的语义也完全相同,都是获取并删除队首元素,区别是当方法失败时前者抛出异常,后者返回null。由于删除操作会改变队列的结构,为维护小顶堆的性质,需要进行必要的调整。

     

    1. public E poll() {
    2. if (size == 0)
    3. return null;
    4. int s = --size;
    5. modCount++;
    6. E result = (E) queue[0];//0下标处的那个元素就是最小的那个
    7. E x = (E) queue[s];
    8. queue[s] = null;
    9. if (s != 0)
    10. siftDown(0, x);//调整
    11. return result;
    12. }

    上述代码首先记录0下标处的元素,并用最后一个元素替换0下标位置的元素,之后调用siftDown()方法对堆进行调整,最后返回原来0下标处的那个元素(也就是最小的那个元素)。重点是siftDown(int k, E x)方法,该方法的作用是从k指定的位置开始,将x逐层向下与当前点的左右孩子中较小的那个交换,直到x小于或等于左右孩子中的任何一个为止。

    1. private void siftDown(int k, E x) {
    2. if (comparator != null)
    3. siftDownUsingComparator(k, x);
    4. else
    5. siftDownComparable(k, x);
    6. }
    7. // siftDownComparable()
    8. private void siftDownComparable(int k, E x) {
    9. Comparablesuper E> key = (Comparablesuper E>) x;
    10. int half = size >>> 1;
    11. while (k < half) {
    12. // 首先找到左右孩子中较小的那个,记录到c里,并用child记录其下标
    13. int child = (k << 1) + 1; // leftNo = parentNo*2+1
    14. Object c = queue[child];
    15. int right = child + 1;
    16. if (right < size &&
    17. comparator.compare((E) c, (E) queue[right]) > 0)
    18. c = queue[child = right];
    19. if (comparator.compare(x, (E) c) <= 0)
    20. break;
    21. queue[k] = c; // 然后用c取代原来的值
    22. k = child;
    23. }
    24. queue[k] = x;
    25. }
    26. private void siftDownUsingComparator(int k, E x) {
    27. int half = size >>> 1;
    28. while (k < half) {
    29. int child = (k << 1) + 1;
    30. Object c = queue[child];
    31. int right = child + 1;
    32. if (right < size &&
    33. comparator.compare((E) c, (E) queue[right]) > 0)
    34. c = queue[child = right];
    35. if (comparator.compare(x, (E) c) <= 0)
    36. break;
    37. queue[k] = c;
    38. k = child;
    39. }
    40. queue[k] = x;
    41. }

    remove(Object o):

    remove(Object o) 方法用于删除队列中跟o相等的某一个元素(如果有多个相等,只删除一个),该方法不是Queue接口内的方法,而是Collection接口的方法。由于删除操作会改变队列结构,所以要进行调整;又由于删除元素的位置可能是任意的,所以调整过程比其它函数稍加繁琐。具体来说,remove(Object o)可以分为2种情况: 1. 删除的是最后一个元素。直接删除即可,不需要调整。2. 删除的不是最后一个元素,从删除点开始以最后一个元素为参照调用一次siftDown()即可。此处不再赘述。

    1. // remove(Object o)
    2. public boolean remove(Object o) {
    3. // 通过遍历数组的方式找到第一个满足o.equals(queue[i])元素的下标
    4. int i = indexOf(o);
    5. if (i == -1)
    6. return false;
    7. else {
    8. removeAt(i);
    9. return true;
    10. }
    11. }
    12. private E removeAt(int i) {
    13. // assert i >= 0 && i < size;
    14. modCount++;
    15. int s = --size;
    16. if (s == i) // removed last element
    17. queue[i] = null;
    18. else {
    19. E moved = (E) queue[s];
    20. queue[s] = null;
    21. siftDown(i, moved);
    22. if (queue[i] == moved) {
    23. siftUp(i, moved);
    24. if (queue[i] != moved)
    25. return moved;
    26. }
    27. }
    28. return null;
    29. }

    2.3. 查找

    peek() 获取但不删除队首元素,也就是队列中权值最小的那个元素,获取不到返回null。根据小顶堆的性质,堆顶那个元素就是全局最小的那个;由于堆用数组表示,根据下标关系,0下标处的那个元素既是堆顶元素。所以直接返回数组0下标处的那个元素即可。

    1. public E peek() {
    2. return (size == 0) ? null : (E) queue[0]; // 0下标处的那个元素就是最小的那个
    3. }

    2.4. 基于集合构造优先队列

    PriorityQueue提供了initFromCollection方法将传入的集合构造成优先队列:

    1. private void initFromCollection(Collection c) {
    2. // 拷贝元素创建初始堆
    3. initElementsFromCollection(c);
    4. // 将初始堆调整为最小(大)二叉堆
    5. heapify();
    6. }
    7. private void initElementsFromCollection(Collection c) {
    8. Object[] a = c.toArray();
    9. // If c.toArray incorrectly doesn't return Object[], copy it.
    10. if (a.getClass() != Object[].class)
    11. a = Arrays.copyOf(a, a.length, Object[].class);
    12. int len = a.length;
    13. if (len == 1 || this.comparator != null)
    14. for (int i = 0; i < len; i++)
    15. if (a[i] == null)
    16. throw new NullPointerException();
    17. this.queue = a;
    18. this.size = a.length;
    19. }
    20. private void heapify() {
    21. for (int i = (size >>> 1) - 1; i >= 0; i--)
    22. siftDown(i, (E) queue[i]);
    23. }

  • 相关阅读:
    notepad++设置中文界面
    【C#】WCF和TCP消息通信练习,实现聊天功能
    MySQL事务隔离与行锁的关系
    没想到我这浓眉大眼的,也有被人催更的一天~
    openarena
    软件测试工程师岗位核心任务
    vagrant设置磁盘大小
    5种常见的软件缺陷分析方法
    元宇宙的实现和落地,需要以AI、VR/AR为代表的诸多新技术的联合加持
    多肽914910-73-9:血管紧张素Angiotensin(1-12)(mouse, rat)
  • 原文地址:https://blog.csdn.net/mrluo735/article/details/133988274