热门标签 | 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的位置
}

 


推荐阅读
  • 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中org.neo4j.helpers.collection.Iterators.single()方法的功能、使用场景及代码示例,帮助开发者更好地理解和应用该方法。 ... [详细]
  • 1:有如下一段程序:packagea.b.c;publicclassTest{privatestaticinti0;publicintgetNext(){return ... [详细]
  • Python 异步编程:深入理解 asyncio 库(上)
    本文介绍了 Python 3.4 版本引入的标准库 asyncio,该库为异步 IO 提供了强大的支持。我们将探讨为什么需要 asyncio,以及它如何简化并发编程的复杂性,并详细介绍其核心概念和使用方法。 ... [详细]
  • 深入解析Android自定义View面试题
    本文探讨了Android Launcher开发中自定义View的重要性,并通过一道经典的面试题,帮助开发者更好地理解自定义View的实现细节。文章不仅涵盖了基础知识,还提供了实际操作建议。 ... [详细]
  • 优化ListView性能
    本文深入探讨了如何通过多种技术手段优化ListView的性能,包括视图复用、ViewHolder模式、分批加载数据、图片优化及内存管理等。这些方法能够显著提升应用的响应速度和用户体验。 ... [详细]
  • 本文详细介绍了 GWT 中 PopupPanel 类的 onKeyDownPreview 方法,提供了多个代码示例及应用场景,帮助开发者更好地理解和使用该方法。 ... [详细]
  • 本文将介绍如何编写一些有趣的VBScript脚本,这些脚本可以在朋友之间进行无害的恶作剧。通过简单的代码示例,帮助您了解VBScript的基本语法和功能。 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • 本文基于刘洪波老师的《英文词根词缀精讲》,深入探讨了多个重要词根词缀的起源及其相关词汇,帮助读者更好地理解和记忆英语单词。 ... [详细]
  • 本文介绍了Java并发库中的阻塞队列(BlockingQueue)及其典型应用场景。通过具体实例,展示了如何利用LinkedBlockingQueue实现线程间高效、安全的数据传递,并结合线程池和原子类优化性能。 ... [详细]
  • 使用Numpy实现无外部库依赖的双线性插值图像缩放
    本文介绍如何仅使用Numpy库,通过双线性插值方法实现图像的高效缩放,避免了对OpenCV等图像处理库的依赖。文中详细解释了算法原理,并提供了完整的代码示例。 ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • 本文详细探讨了Java中的24种设计模式及其应用,并介绍了七大面向对象设计原则。通过创建型、结构型和行为型模式的分类,帮助开发者更好地理解和应用这些模式,提升代码质量和可维护性。 ... [详细]
  • CentOS7源码编译安装MySQL5.6
    2019独角兽企业重金招聘Python工程师标准一、先在cmake官网下个最新的cmake源码包cmake官网:https:www.cmake.org如此时最新 ... [详细]
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社区 版权所有