java 优先队列

Every now and then we need to process items of a queue in a particular order. Priority queue is a Data Structure that does the job. Java priority queue is different from “normal” queue. Instead of “First-In-First-Out”, it retrieves the items in order of their priority.

我们有时需要按特定顺序处理队列中的项目。 优先级队列是完成任务的数据结构。 Java优先级队列与“普通” 队列不同 。 代替“先进先出”,它按优先级顺序检索项目。

优先队列Java (Priority Queue Java)

The java.util.PriorityQueue class, provides us an implementation of such a data type, by using priority heap implementation internally. Java PriorityQueue is an unbounded queue. It was introduced in Java 1.5 and enhanced in Java SE 8 release. PriorityQueue is internally implemented by following “Priority Heap” data structure.

java.util.PriorityQueue类通过内部使用优先级堆实现为我们提供了这种数据类型的实现。 Java PriorityQueue是一个无界队列。 它是在Java 1.5中引入的,并在Java SE 8版本中得到了增强。 PriorityQueue通过遵循“ Priority Heap”数据结构在内部实现。

Here is the PriorityQueue class hierarchy:

这是PriorityQueue类层次结构:

PriorityQueue Class Diagram:

PriorityQueue类图:

Java PriorityQueue构造函数 (Java PriorityQueue Constructors)

  1. PriorityQueue() – Creates a PriorityQueue with the default initial capacity, i.e. 11PriorityQueue() –使用默认初始容量(即11 创建一个PriorityQueue
  2. PriorityQueue(Collection c) – Creates a PriorityQueue with the elements in the specified collectionPriorityQueue(Collection c) –使用指定集合中的元素创建一个PriorityQueue
  3. PriorityQueue(int initialCapacity) – Creates a PriorityQueue with the specified initial capacityPriorityQueue(int initialCapacity) –创建具有指定初始容量的PriorityQueue
  4. PriorityQueue(int initialCapacity, Comparator comparator) – Creates a PriorityQueue with the provided initial capacity and the ordering of its elements is according to the specified comparatorPriorityQueue(int initialCapacity,Comparator比较器) –创建具有提供的初始容量的PriorityQueue,其元素的顺序根据指定的比较器
  5. PriorityQueue(PriorityQueue c) – Creates a PriorityQueue containing the elements in the specified priority queuePriorityQueue(PriorityQueue c) –创建一个包含指定优先级队列中元素的PriorityQueue
  6. PriorityQueue(SortedSet c) – Creates a PriorityQueue containing the elements in the specified sorted setPriorityQueue(SortedSet c) –创建一个包含指定排序集中的元素的PriorityQueue

Priority Queue elements are ordered by their natural ordering unless we provide a Comparator while creating it.
The elements are ordered in ascending order by default, hence the head of the queue is the element whose priority is lowest.

除非我们在创建Comparator时提供它,否则Priority Queue元素将按照其自然顺序进行排序。
默认情况下,元素按升序排列,因此队列的开头是优先级最低的元素。

If there are two elements which are eligible to become the head at the same time, this kind of ties are broken arbitrarily.

如果有两个元素可以同时成为负责人,则这种联系会被任意打破。

Java PriorityQueue示例 (Java PriorityQueue Example)

Let’s create a PriorityQueue, containing various tasks:

让我们创建一个PriorityQueue ,其中包含各种任务:

PriorityQueue tasks=new PriorityQueue();
tasks.add("task1");
tasks.add("task4");
tasks.add("task3");
tasks.add("task2");
tasks.add("task5");

This creates a PriorityQueue of tasks, which will be ordered by the natural ordering of String.
Let’s create another PriorityQueue which orders the tasks in reverse order of natural ordering. So we need to pass a Comparator:

这将创建一个PriorityQueue任务,该任务将按String的自然顺序进行排序。
让我们创建另一个PriorityQueue,它以自然顺序的相反顺序对任务进行排序。 因此,我们需要通过一个比较器:

PriorityQueue reverseTasks=new PriorityQueue(Comparator.reverseOrder());
reverseTasks.add("task1");
reverseTasks.add("task4");
reverseTasks.add("task3");
reverseTasks.add("task2");
reverseTasks.add("task5");

Java PriorityQueue方法 (Java PriorityQueue Methods)

Now, let’s take a look at all the methods available for PriorityQueue and use them:

现在,让我们看一下PriorityQueue可用的所有方法并使用它们:

  1. Boolean add(E e) – This method inserts the specified element in the queue.
    We have already added 5 tasks in our queue using this method.布尔值add(E e) –此方法将指定的元素插入队列。
    我们已经使用这种方法在队列中添加了5个任务。
  2. Comparator comparator() – This method returns the Comparator used to order the elements in this queue. It returns null if no comparator was specified and the queue is sorted according to the natural ordering of its elements.
    So, if we do:

    System.out.println(tasks.comparator());
    System.out.println(reverseTasks.comparator());

    The output will be:

    比较器比较器() -此方法返回用于对队列中的元素进行排序的比较器 。 如果未指定比较器,并且队列根据其元素的自然顺序排序,则返回null。
    因此,如果我们这样做:

    System.out.println(tasks.comparator());
    System.out.println(reverseTasks.comparator());

    输出将是:

  3. boolean contains(Object o) – Returns true if the queue contains the specified element.
    Let’s check if “task3” belongs to the Priority queue tasks:

    System.out.println(tasks.contains("task3"));

    This prints:

    boolean contains(Object o) –如果队列包含指定的元素,则返回true。
    让我们检查“ task3”是否属于优先级队列任务:

    System.out.println(tasks.contains("task3"));

    打印:

  4. boolean offer(E e) – Just like the add() method, this method also adds an element to the queue.
    The offer() and add() methods are actually a bit different for capacity constrained queues, but in case of PriorityQueue, both are same. Unlike add(), offer() does not throw an exception even if it fails to add the element in the queue.boolean offer(E e) –就像add()方法一样,此方法也将元素添加到队列中。
    对于容量受限制的队列,offer()和add()方法实际上有些不同,但是对于PriorityQueue,两者是相同的。 与add()不同,即使offer()无法将元素添加到队列中,它也不会引发异常。
  5. E peek() – Retrieves the head of this queue, or returns null if this queue is empty. In other words, it returns the element with highest priority.
    So the following code:

    System.out.println(tasks.peek());
    System.out.println(reverseTasks.peek());

    Gives us:

    E peek() –检索此队列的开头,如果此队列为空,则返回null。 换句话说,它返回具有最高优先级的元素。
    所以下面的代码:

    System.out.println(tasks.peek());
    System.out.println(reverseTasks.peek());

    给我们:

  6. E poll() – This method also retrieves the head of the queue(element with highest priority), or returns null if the queue is empty. But unlike peek(), it also removes the element.
    So, if we call poll():

    System.out.println(“Poll on tasks: ”+tasks.poll());
    System.out.println(“Poll on reverseTasks: ”+reverseTasks.poll());

    And then peek:

    We’ll have the following outptut:

    Poll on tasks: task1
    Poll on reverseTasks: task5
    Peek on tasks: task2
    Peek on reverseTasks: task4

    E poll() –此方法还检索队列的头部(具有最高优先级的元素),如果队列为空,则返回null。 但是与peek()不同,它还删除了元素。
    因此,如果我们调用poll():

    然后偷看:

    System.out.println(“Peek on tasks: ”+tasks.peek());
    System.out.println(“Peek on reverseTasks: ”+reverseTasks.peek());

    我们将提供以下输出:

  7. int size() – Returns the number of elements in the queue.int size() –返回队列中元素的数量。
  8. boolean remove(Object o) – Removes the specified element from the queue, if it’s present. If two same elements are present, it only removes one of them.boolean remove(Object o) -从队列中删除指定的元素(如果存在)。 如果存在两个相同的元素,则仅删除其中之一。
  9. Object[] toArray() – Returns an array containing all the elements in the queue.Object [] toArray() –返回包含队列中所有元素的数组。
  10. T[] toArray(T[] a) – Returns an array containing all the elements in the queue, and the type of the returned array is that of the specified array.T [] toArray(T [] a) –返回包含队列中所有元素的数组,并且返回的数组的类型为指定数组的类型。
  11. Iterator iterator() – Returns an iterator for the queue.Iterator iterator() –返回队列的迭代器。
  12. void clear() – Removes all of the elements from the queue.void clear() –从队列中删除所有元素。

Apart from these, the PriorityQueue also inherits the methods from the Collection and Object classes.

除此之外, PriorityQueue还继承了CollectionObject类的方法。

Java PriorityQueue时间复杂度 (Java PriorityQueue Time Complexity)

  1. For enqueing and dequeing methods, the time complexity is O(log(n))对于入队和出队方法,时间复杂度为O(log(n))
  2. For the remove(Object) and contains(Object) methods, the time complexity is linear对于remove(Object)和contains(Object)方法,时间复杂度是线性的
  3. For the retrieval methods, it has constant time complexity对于检索方法,它具有恒定的时间复杂度

This implementation of priority queue is not thread-safe. So, if we need synchronised access, we need to use PriorityBlockingQueue.

优先级队列的此实现不是线程安全的。 因此,如果需要同步访问,则需要使用PriorityBlockingQueue 。

Reference: API Doc

参考: API文档

翻译自: https://www.journaldev.com/16254/priority-queue-java

java 优先队列

java 优先队列_优先队列Java相关推荐

  1. Java算法_优先队列和PriorityQueue——HDU 1873:看病要排队

    目录 优先队列和PriorityQueue HDU 1873:看病要排队 java.util.Comparator 优先队列和PriorityQueue java.util.PriorityQueue ...

  2. 易语言 java支持_开源Java客户端可以连接易语言服务器

    我们的服务端处理客户端的连接请求是同步进行的, 每次接收到来自客户端的连接请求后, 都要先跟当前的客户端通信完之后才能再处理下一个连接请求. 这在并发比较多的情况下会严重影响程序的性能, 为此,我们可 ...

  3. 尚学堂java培训_送给 Java 自学者或者初学者的最全知识清单,2020 年 Java 就该这么学...

    最近逛知乎,发现有很多想自学 Java 或者 Java 初学者提问,不知道如何学习 Java?我接触 Java 快 8 年的时间了,一直从事 Java 开发工作,自己一直升级打怪,对于如何更好的学习 ...

  4. java 模板方法_设计模式(java实现)_模板方法模式(Template method)

    设计模式(java实现)_模板方法模式(Template method) 模板方法模式是编程中经常用到到的模式.它定义了一个操作中的算法骨架,将某些步骤延迟到子类中实现.这样,新的子类可以在不改变一个 ...

  5. java安装_使用Java 9模块化来发布零依赖本机应用程序

    java安装 为什么我不能仅构建一个.EXE? 首次引入Java时,主流编程语言大多要么编译成独立的可执行文件(例如C / C ++,COBOL),要么在解释器中运行(例如Perl,Tcl). 对于许 ...

  6. java转账_使用Java模拟银行账户存、取款、转账功能

    半枯 package bank;import java.util.Scanner;/** * 1.建立一个银行账户类(Acount),具有建立新帐号.查询余额.存款.取款.转账 * 即从本账户把钱转给 ...

  7. java预期_预期. java的

    我有这段java代码.我是java中的菜鸟.. 错误: expected cfg = new Config; 码: import java.sql.Connection; import java.sq ...

  8. python能解密java的_实现Java加密,Python解密的RSA非对称加密算法功能

    摘要 因为最近业务需要使用到openssl的rsa非对称加密算法,研究了下它的使用方式,但是特殊在于前端分IOS和android两端,所以前端部门要求使用java给他们做一个加密工具包,但是因为服务端 ...

  9. java书籍_学习Java最好的10本书,从入门到精通

    在当代,学习Java等编程课程的主要方式是视频资源,如果你想学,在网上五分钟之内就可以找到一堆学习视频,瞬间将你的硬盘填满.但是这些课程质量良莠不齐,对于小白来说很难辨别好坏. 但是书籍不同,书籍都是 ...

  10. java 方块_哈工大java实验 移动小方块

    /*java第二次实验 * 移动小方块 */ import javax.swing.*; import java.awt.event.*; import java.awt.geom.*; import ...

最新文章

  1. 十三、linux编程中目录IO常用编程函数
  2. sql 数组_sql注入中级
  3. css中margin:0 auto没作用
  4. 【codevs1068】乌龟棋noip10年TG----第二个A掉的钻石题
  5. Redis 缓存过期(maxmemory) 配置/算法 详解
  6. C++ 常见错误(03) —— cout输出图像路径
  7. python清空屏幕代码_python代码怎样清屏
  8. vfp保存为html,vfp向HTTP发送文件
  9. flash将文本呈现为html,flash中的静态文本、动态文本、输入文本
  10. mysql 拼音排序_mysql汉字字段按拼音排序的方法
  11. python开发微信点餐_微信点餐平台开发 (一)
  12. Android车载应用开发与分析(11)- 车载Android应用开发入门指南
  13. php越权执行命令漏洞_泛微OA系统多版本存在命令执行漏洞
  14. Ambari集群里操作时典型权限问题put: `/home/bigdata/1.txt‘: No such file or directory的解决方案(图文详解)
  15. 基于讯飞语音引擎3.0.apk的Android原生TTS
  16. Echarts地图版块移动位置的解决方案
  17. android sd 挂载流程_Android7.0 SD卡挂载流程
  18. 【学习笔记】Tensorflow-ENet代码学习(一)
  19. Python爬虫实战之爬取QQ音乐之下载有版权的音乐(五)-1
  20. Carsim汽车AEB测试

热门文章

  1. BZOJ1075 : [SCOI2007]最优驾车drive
  2. iOS安全系列之一:HTTPS
  3. pcie inbound、outbound及EP、RC间的互相訪问
  4. ASP.NET MVC5+EF6+EasyUI 后台管理系统(28)-系统小结
  5. sql2005数据库备份—sql语句
  6. .Net 1.1 到 .Net 2.0 开发日志
  7. [转载] python中string函数的用法_python中string模块各属性以及函数的用法
  8. [转载] 如何使用Python 实现秒表功能?
  9. 44 The shopping psychology 购物心理
  10. CPP-week fourteen