Java Priority Queue(PriorityQueue)示例

我们知道, 队列如下:F irst- ˚First-ØUT模型,但有时我们需要处理的基础上,优先级队列中的对象。 例如,假设我们有一个应用程序可以为日常交易生成股票报告,并处理大量数据并花费时间来处理它。 因此,客户正在将请求发送到实际上正在排队的应用程序,但是我们要先处理高级客户,然后再处理标准客户。 因此,在这种情况下,用Java实现PriorityQueue确实很有帮助。

PriorityQueue类在Java 1.5中引入,并且是Java Collections Framework的一部分。 PriorityQueue是基于优先级堆的无界队列,并且默认情况下优先级队列的元素以自然顺序排序,或者我们可以在队列实例化时提供Comparator进行排序。

PriorityQueue不允许使用值,并且我们无法创建不可比对象的PriorityQueue,例如我们拥有的任何自定义类。 我们使用java Comparable和Comparator接口对对象进行排序,而PriorityQueue使用它们对元素的优先级进行处理。

优先级队列的头是基于自然排序或基于比较器排序的最小元素,如果有多个具有相同排序的对象,则它可以随机轮询其中的任何一个。 当我们轮询队列时,它从队列中返回头对象。

PriorityQueue大小不受限制,但是我们可以在创建时指定初始容量。 当我们将元素添加到优先级队列时,它的容量会自动增长。

PriorityQueue 不是线程安全的 ,因此Java提供了PriorityBlockingQueue类,该类实现了BlockingQueue接口以在Java多线程环境中使用。

PriorityQueue实现为入队和出队方法提供O(log(n))时间。 让我们来看一个自然排序以及Comparator的PriorityQueue示例。

我们有自定义类Customer ,它不提供任何类型的排序,因此,当我们尝试将其与PriorityQueue一起使用时,应为此提供一个比较器对象。

package com.journaldev.collections;public class Customer {private int id;private String name;public Customer(int i, String n){this.id=i;this.name=n;}public int getId() {return id;}public String getName() {return name;}}

我们将使用Java随机数生成来生成随机的客户对象。 对于自然排序,我将使用Integer,它也是一个Java包装器类 。

这是我们的最终测试代码,显示了如何使用PriorityQueue。

package com.journaldev.collections;import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;public class PriorityQueueExample {public static void main(String[] args) {//natural ordering example of priority queueQueue<Integer> integerPriorityQueue = new PriorityQueue<>(7);Random rand = new Random();for(int i=0;i<7;i++){integerPriorityQueue.add(new Integer(rand.nextInt(100)));}for(int i=0;i<7;i++){Integer in = integerPriorityQueue.poll();System.out.println("Processing Integer:"+in);}//PriorityQueue example with ComparatorQueue<Customer> customerPriorityQueue = new PriorityQueue<>(7, idComparator);addDataToQueue(customerPriorityQueue);pollDataFromQueue(customerPriorityQueue);}//Comparator anonymous class implementationpublic static Comparator<Customer> idComparator = new Comparator<Customer>(){@Overridepublic int compare(Customer c1, Customer c2) {return (int) (c1.getId() - c2.getId());}};//utility method to add random data to Queueprivate static void addDataToQueue(Queue<Customer> customerPriorityQueue) {Random rand = new Random();for(int i=0; i<7; i++){int id = rand.nextInt(100);customerPriorityQueue.add(new Customer(id, "Pankaj "+id));}}//utility method to poll data from queueprivate static void pollDataFromQueue(Queue<Customer> customerPriorityQueue) {while(true){Customer cust = customerPriorityQueue.poll();if(cust == null) break;System.out.println("Processing Customer with ID="+cust.getId());}}}

请注意,我正在使用java匿名类来实现Comparator接口并创建基于id的比较器。

当我在测试程序上运行时,得到以下输出:

Processing Integer:9
Processing Integer:16
Processing Integer:18
Processing Integer:25
Processing Integer:33
Processing Integer:75
Processing Integer:77
Processing Customer with ID=6
Processing Customer with ID=20
Processing Customer with ID=24
Processing Customer with ID=28
Processing Customer with ID=29
Processing Customer with ID=82
Processing Customer with ID=96

从输出中可以明显看出,最少的元素在首位,并且被首先轮询。 如果在创建customerPriorityQueue时不提供比较器,它将在运行时引发ClassCastException。

Exception in thread "main" java.lang.ClassCastException: com.journaldev.collections.Customer cannot be cast to java.lang.Comparableat java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:633)at java.util.PriorityQueue.siftUp(PriorityQueue.java:629)at java.util.PriorityQueue.offer(PriorityQueue.java:329)at java.util.PriorityQueue.add(PriorityQueue.java:306)at com.journaldev.collections.PriorityQueueExample.addDataToQueue(PriorityQueueExample.java:45)at com.journaldev.collections.PriorityQueueExample.main(PriorityQueueExample.java:25)

参考: Java优先级队列(PriorityQueue)示例,来自我们的JCG合作伙伴 Pankaj Kumar,位于Developer Recipes博客上。

翻译自: https://www.javacodegeeks.com/2013/07/java-priority-queue-priorityqueue-example.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/367666.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

css未知尺寸的图片的水平和垂直居中

纯CSS实现未知尺寸的图片水平和垂直居中.box { /*非IE的主流浏览器识别的垂直居中的方法*/ display: table-cell; vertical-align:middle; /*设置水平居中*/ text-align:center; /* 针对IE的Hack */ *display: block; *font-size:26…

heap 的一些用法

noip 合并果子 #include<bits/stdc.h> using namespace std; int heap[maxn]; int size0; void input(int d) {heap[size]d;push_heap(heap,heapsize,greater<int>()); } int get() {pop_heap(heap,heapsize,greater<int>());//pop_heap(heap,heapsize);ret…

java 反射 new class_Java高级特性-反射:不写死在代码,还怎么 new 对象?

反射是 Java 的一个高级特性&#xff0c;大量用在各种开源框架上。在开源框架中&#xff0c;往往以同一套算法&#xff0c;来应对不同的数据结构。比如&#xff0c;Spring 的依赖注入&#xff0c;我们不用自己 new 对象了&#xff0c;这工作交给 Spring 去做。然而&#xff0c;…

EF Core利用Scaffold从根据数据库生成代码

在EF6 之前的时代&#xff0c;如果需要从数据库中生成代码&#xff0c;是可以直接在界面上操作的&#xff0c;而到了EF Core的时代&#xff0c;操作方式又有更简便的方式了&#xff0c;我们只需要记住以下这条指令。 Scaffold-DbContext "Server服务器地址;Database数据库…

如何通过CSS开启硬件加速来提高网站性能

你知道我们可以在浏览器中用css开启硬件加速&#xff0c;使GPU (Graphics Processing Unit) 发挥功能&#xff0c;从而提升性能吗&#xff1f; 现在大多数电脑的显卡都支持硬件加速。鉴于此&#xff0c;我们可以发挥GPU的力量&#xff0c;从而使我们的网站或应用表现的更为流畅…

Spring Security应用程序中的su和sudo

很久以前&#xff0c;我从事的项目具有很强大的功能。 有两个角色&#xff1a;用户和主管。 主管可以以任何方式更改系统中的任何文档&#xff0c;而用户则更受工作流约束的限制。 当普通用户对当前正在编辑和存储在HTTP会话中的文档有疑问时&#xff0c;主管可以介入&#xff…

示例介绍:JavaFX 8打印

我有一段时间没有写博客了&#xff0c;我想与其他人分享有关JavaFX的所有信息&#xff08;我的日常工作和家庭可能是借口&#xff09;。 对于那些是本博客的新手&#xff0c;我是JavaFX 2 Introduction by Example&#xff08;JIBE&#xff09;的作者&#xff0c; Java 7 Recip…

placeholder的使用

1.定义 placeholder 属性提供可描述输入字段预期值的提示信息 该提示会在输入字段为空时显示&#xff0c;并会在字段获得焦点时消失。 注释&#xff1a;placeholder 属性适用于以下的 <input> 类型&#xff1a;text, search, url, telephone, email 以及 password。 2.用…

字符串练习

字符串练习&#xff1a; http://news.gzcc.cn/html/2017/xiaoyuanxinwen_1027/8443.html 取得校园新闻的编号 trhttp://news.gzcc.cn/html/2017/xiaoyuanxinwen_1027/8443.html print(a[-14:-5])https://docs.python.org/3/library/turtle.html 产生python文档的网址 trhttps:/…

CSS清除行内元素之间的HTML空白

至今我还记得年轻是在IE6上开发的那些苦逼日子,特别希望IE浏览器采用 inline-block 的显示方式.行内块(inline-block)是非常有用的,特别是想要不用block和float来控制这些行内元素的margin,padding之时。问题来了,HTML源码中行内元素之间的空白有时候显示在屏幕上那是相当的讨厌…

int64 java_为什么json 不能使用 int64类型

json 简介jsON(JavaScript Object Notation) 是一种轻量级的数据交换格式。 易于人阅读和编写。同时也易于机器解析和生成。 它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集 。 JSON采用完全独立于语言的文本格式&#xff0…

Spring MVC自定义验证注释

在上一教程中&#xff0c;我展示了如何使用注释来验证表单 。 这对于简单的验证非常有用&#xff0c;但是最终&#xff0c;您需要验证一些现成的注释中没有的自定义规则。 例如&#xff0c;如果您需要根据输入的出生日期来验证用户已超过21岁&#xff0c;或者可能需要验证用户的…

Best Time to Buy and Sell Stock with Cooldown

https://soulmachine.gitbooks.io/algorithm-essentials/java/dp/best-time-to-buy-and-sell-stock-with-cooldown.html转载于:https://www.cnblogs.com/ZhiHao-queue/p/9521933.html

前期

转载于:https://www.cnblogs.com/joker157/p/8618091.html

解决IE8下body{ overflow:hidden;}无效的解决办法

css中IE8 body{ overflow:hidden;}无效的解决办法&#xff1a; 在页面html中使用: body{ overflow:hidden; } 在ie8下无效 &#xff0c;仍然有滚动条。 解决的办法如下&#xff1a; 替换为如下: html { overflow:hidden; } 这样就可以实现隐藏滚动条了 而且兼容目前所有的浏览器…

0基础能学mysql数据库吗_mysql学习入门:零基础如何使用mysql创建数据库表?

零基础如何自学Mysql创建数据库&#xff0c;是Mysql学习者必经之路&#xff0c;Mysql是受欢迎的关系数据库管理系统,WEB应用方面MySQL是很好的RDBMS应用软件之一。如何使用Mysql创建数据库表&#xff0c;打开Mysql学习进阶大门&#xff0c;就是今天MYSQL学习教程丁光辉博客认为…

使用ANTLR和Java创建外部DSL

在以前的一段时间里&#xff0c;我曾写过有关使用Java的内部DSL的文章。 在Martin Fowler撰写的《 领域特定语言 》一书中&#xff0c;他讨论了另一种称为外部DSL的DSL&#xff0c;其中DSL是用另一种语言编写的&#xff0c;然后由宿主语言进行解析以填充语义模型。 在前面的示…

vue跨域解决及打包

打包之前需要修改如下配置文件&#xff1a; 配置文件一&#xff1a;build>>>utils.js (修改publicPath:"../../" , 这样写是处理打包后找不到静态文件&#xff08;图片路径失效&#xff09;的问题) 配置文件二&#xff1a;config>>>index.js(修改a…

8. Oracle 联机重做日志文件(ONLINE LOG FILE)

转载自&#xff1a;http://blog.csdn.net/leshami/article/details/5749556 一、Oracle中的几类日志文件 Redo log files -->联机重做日志 Archive log files -->归档日志 Alert log files -->告警日志 Trace files -->跟踪日志 user_dump_…

Bootstrap中实现图片圆角效果

Bootstrap 对图片的支持。Bootstrap 提供了三个可对图片应用简单样式的 class&#xff1a; .img-rounded&#xff1a;添加 border-radius:6px 来获得图片圆角。.img-circle&#xff1a;添加 border-radius:500px 来让整个图片变成圆形。.img-thumbnail&#xff1a;添加一些内边…