热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

PriorityQueue源码分析

 publicbooleanhasNext(){returncursor<size||(forgetMeNot!null&am

PriorityQueue 源码分析

 

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

        //内部的迭代器,就是数组的迭代,迭代指针cursor,
        public E next() {
            if (expectedModCount != modCount)
                throw new ConcurrentModificationException();
            if (cursor < size)
                return (E) queue[lastRet = cursor++];
            if (forgetMeNot != null) {
                lastRet = -1;
                lastRetElt = forgetMeNot.poll();
                if (lastRetElt != null)
                    return lastRetElt;
            }
            throw new NoSuchElementException();
        }

PriorityQueue 源码分析

扩容:
private void grow(int minCapacity) {
        int oldCapacity = queue.length;
        // 小于64扩大为原来2倍,大于等于64扩大为原来1.5倍,
        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);//丢弃原来的数组,指向新的数组,
    }
public class zusheQueue {
private static PriorityQueue queue = new PriorityQueue(3);


  public static void main(String[] args)  {
   queue.offer(80);
   queue.offer(60);
   queue.offer(70);
   queue.offer(40);
   queue.offer(20);
   queue.offer(10);
   queue.offer(90);
   queue.offer(22);
   queue.offer(15);
   queue.offer(4);
   queue.offer(1);
   System.out.println(queue);//[1, 4, 20, 22, 10, 70, 90, 80, 40, 60, 15]   数组实现最小堆
    System.out.println("出来 "+queue.poll());
    System.out.println("出来 "+queue.poll());
    System.out.println("出来 "+queue.poll());
    System.out.println("出来 "+queue.poll());
    /*出来 1
    出来 4
    出来 10
    出来 15    出来最小的*/
    System.out.println(queue);
    
    
    Iterator i = queue.iterator();
    while(i.hasNext()) {
          System.out.print(i.next() + " ");//1 4 20 22 10 70 90 80 40 60 15 
       }
       
       
    List l = Arrays.asList(7,85,4,9,5,85,74,5,8);
    PriorityQueue p = new PriorityQueue<>(l);
    System.out.println(p);
  }
    
}

PriorityQueue 源码分析

PriorityQueue 源码分析

private void siftUpComparable(int k, E x) {
    Comparablesuper E> key = (Comparablesuper E>) 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;
}

PriorityQueue 源码分析

PriorityQueue 源码分析

PriorityQueue 源码分析

PriorityQueue 源码分析

PriorityQueue 源码分析

PriorityQueue 源码分析

PriorityQueue 源码分析

private void siftDownComparable(int k, E x) { // k = 0
        Comparablesuper E> key = (Comparablesuper E>)x;
        int half = size >>> 1;        // 非叶子节点
        while (k < half) {
            int child = (k <<1) + 1;   // child = 左孩子
            Object c = queue[child]; // c = 左孩子
            int right = child + 1;//right = 右孩子
            if (right 
                ((Comparablesuper E>) c).compareTo((E) queue[right]) > 0)  //有右孩子,并且左孩子大于右孩子
                c = queue[child = right];// c = 右孩子,child = 右孩子
            if (key.compareTo((E) c) <= 0)  //key小于右孩子,就是小于所有孩子
                break; //结束循环
            queue[k] = c; //  否则key大于右孩子,k位置是右孩子,就是较小的孩子
            k = child;  //指针k值为right右孩子的位置, 比较都是根据指针位置比较,放的时候才放对象。
        }
        queue[k] = key;
    }

PriorityQueue 源码分析

PriorityQueue 源码分析

PriorityQueue 源码分析

构造函数:

PriorityQueue 源码分析

public PriorityQueue(Collectionextends E> c) {
    if (c instanceof SortedSet) {
        SortedSetextends E> ss = (SortedSetextends E>) c;
        this.comparator = (Comparatorsuper E>) ss.comparator();
        initElementsFromCollection(ss);
    }
    else if (c instanceof PriorityQueue) {
        PriorityQueueextends E> pq = (PriorityQueueextends E>) c;
        this.comparator = (Comparatorsuper E>) pq.comparator();
        initFromPriorityQueue(pq);
    }
    else {
        this.comparator = null;
        initFromCollection(c);
    }
}
private void initFromCollection(Collectionextends E> c) {
    initElementsFromCollection(c);
    heapify();
}
private void initElementsFromCollection(Collectionextends E> c) {
    Object[] a = c.toArray();
    // If c.toArray incorrectly doesn't return Object[], copy it.
    if (a.getClass() != Object[].class)
        a = Arrays.copyOf(a, a.length, Object[].class);
    int len = a.length;
    if (len == 1 || this.comparator != null)
        for (int i = 0; i )
            if (a[i] == null)
                throw new NullPointerException();
    this.queue = a;
    this.size = a.length;
}
private void heapify() {
    for (int i = (size >>> 1) - 1; i >= 0; i--)   //(size >>> 1) - 1就是找到第一个非叶子节点,然后从下到上从右到左,
        siftDown(i, (E) queue[i]);
}

PriorityQueue 源码分析

PriorityQueue 源码分析

 

public E poll() {
    if (size == 0)
        return null;
    int s = --size;
    modCount++;
    E result = (E) queue[0];   //取出第0个元素
    E x = (E) queue[s];     //取出最后一个元素
    queue[s] = null;   // 最后一个元素置为空
    if (s != 0)
        siftDown(0, x);   //  最后一个元素不要先不要放在第0个元素位置,比较之后确定位置了再放。放置的都是左右孩子,改变的是k的值,key不到最后不放。
    return result;  //返回第0个元素
}
private void siftDownComparable(int k, E x) {
    Comparablesuper E> key = (Comparablesuper E>)x;    
    int half = size >>> 1;      
    while (k < half) {
        // sI, sV是左右子节点的较小位置和值,k,key是要比较的元素和准备放的位置(落之前要比较在放)
        int sI = (k <<1) + 1; // 较小位置=左孩子索引
        Object sV = queue[sI];//较小值=左孩子
        int right = sI+ 1; 
        if (right 
            ((Comparablesuper E>) sV ).compareTo((E) queue[right]) > 0)   //有右孩子,并且左孩子大于右孩子,
            sV  = queue[sI= right];     //  较小位置=右孩子索引,较小值=右孩子,
        if (key.compareTo((E) sV ) <= 0)    //key比左右都小,放上去,
            break;
        queue[k] = sV ;//否则key比子节点要大,交换位置,并且自己准备放在sl的位置。放置的都是左右孩子,改变的是k的值,key不到最后不放。
        k = sI;  //自己放在sl的位置之前,也要跟子节点比较一下,在放。
    }
    queue[k] = key;//key放在k的位置
}

 


推荐阅读
  • 本文介绍了Java并发库中的阻塞队列(BlockingQueue)及其典型应用场景。通过具体实例,展示了如何利用LinkedBlockingQueue实现线程间高效、安全的数据传递,并结合线程池和原子类优化性能。 ... [详细]
  • 本文介绍如何使用Objective-C结合dispatch库进行并发编程,以提高素数计数任务的效率。通过对比纯C代码与引入并发机制后的代码,展示dispatch库的强大功能。 ... [详细]
  • 本文详细介绍了 Apache Jena 库中的 Txn.executeWrite 方法,通过多个实际代码示例展示了其在不同场景下的应用,帮助开发者更好地理解和使用该方法。 ... [详细]
  • 题目Link题目学习link1题目学习link2题目学习link3%%%受益匪浅!-----&# ... [详细]
  • 由二叉树到贪心算法
    二叉树很重要树是数据结构中的重中之重,尤其以各类二叉树为学习的难点。单就面试而言,在 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • Java 类成员初始化顺序与数组创建
    本文探讨了Java中类成员的初始化顺序、静态引入、可变参数以及finalize方法的应用。通过具体的代码示例,详细解释了这些概念及其在实际编程中的使用。 ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • 本文提供了使用Java实现Bellman-Ford算法解决POJ 3259问题的代码示例,详细解释了如何通过该算法检测负权环来判断时间旅行的可能性。 ... [详细]
  • 本题探讨如何通过最大流算法解决农场排水系统的设计问题。题目要求计算从水源点到汇合点的最大水流速率,使用经典的EK(Edmonds-Karp)和Dinic算法进行求解。 ... [详细]
  • 丽江客栈选择问题
    本文介绍了一道经典的算法题,题目涉及在丽江河边的n家特色客栈中选择住宿方案。两位游客希望住在色调相同的两家客栈,并在晚上选择一家最低消费不超过p元的咖啡店小聚。我们将详细探讨如何计算满足条件的住宿方案总数。 ... [详细]
  • 本文介绍了如何在 C# 和 XNA 框架中实现一个自定义的 3x3 矩阵类(MMatrix33),旨在深入理解矩阵运算及其应用场景。该类参考了 AS3 Starling 和其他相关资源,以确保算法的准确性和高效性。 ... [详细]
author-avatar
chroalist
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有