---
title: "PriorityQueue的使用"
author: "speed847"
date: "2014-05-29T12:14:39Z"
tags: []
categories: ["互联网"]
slug: "priorityqueue"
draft: false
lastmod: "2014-05-29T12:15:09Z"
id: 2073395
url: "https://speed847.iteye.com/blog/2073395"
---

# [http://blog.csdn.net/yangzhongblog/article/details/8607632](http://blog.csdn.net/yangzhongblog/article/details/8607632)

# 1 概念

  优先级队列PriorityQueue是不同于先进先出队列的另一种队列，每次从队列中取出的是具有最高优先权的元素。优先队列可用有序数组或堆实现，但是常用堆来实现，下面是2种实现效率的比较：

![](http://img.my.csdn.net/uploads/201302/24/1361716265_2691.jpg)

![](http://img.my.csdn.net/uploads/201302/24/1361716296_7174.jpg)

**使用：用于获取优先权最高的元素。**

例如：在1000个数中找到最大的那个数。如果用快速排序对数就行排序，时间复杂度是O(NlogN)；而用优先队列（用队实现）存储数据，然后取出最大元素（此处为优先权最大的元素）这种数据结构时间复杂度为O（logN）。

# []()**2 java.util.PriorityQueue方法**

  java.util.PriorityQueue是从JDK1.5开始提供的新的数据结构接口。如果不提供Comparator的话，优先队列中元素默认按自然顺序排列，也就是数字默认是小的在队列头，字符串则按字典序排列。优先级队列不允许 null 元素。其提供的方法如下：

![](http://img.my.csdn.net/uploads/201302/24/1361716767_6637.jpg)

![](http://img.my.csdn.net/uploads/201302/24/1361717137_4138.jpg)

 

# []()3 使用例子

定义存储对象

 

**\[java]** [view plain](http://blog.csdn.net/yangzhongblog/article/details/8607632 "view plain")[copy](http://blog.csdn.net/yangzhongblog/article/details/8607632 "copy")

 

01. &lt;span style="font-size:18px;"&gt;package zyang.priorityQueue;
02. /\**
03. * Fuction:
04. * @version  2013-2-24 下午8:15:59
05. * @since    1.0
06. \*/
07. public class Student {
08. private int number;
09. private String name;
10. public Student(int number,String name){
11. this.number=number;
12. this.name=name;
13. }
14. public int getNumber() {
15. return number;
16. }
17. public void setNumber(int number) {
18. this.number = number;
19. }
20. public String getName() {
21. return name;
22. }
23. public void setName(String name) {
24. this.name = name;
25. }
26. @Override
27. public String toString() {
28. return "Student \[number=" + number + ", name=" + name + "]";
29. }
30. }
31. &lt;/span&gt;

定义比较器

 

 

**\[java]** [view plain](http://blog.csdn.net/yangzhongblog/article/details/8607632 "view plain")[copy](http://blog.csdn.net/yangzhongblog/article/details/8607632 "copy")

 

01. &lt;span style="font-size:18px;"&gt;package zyang.priorityQueue;
02. import java.util.Comparator;
03. /\**
04. * Fuction:
05. * 按学号排序 先按学号排序，学号相等时，按姓名排序 o1&gt;o2返回-1，o1=o2返回0，o1&lt;o2返回1
06. * @author
07. * @version  2013-2-24 下午8:16:26
08. * @since    1.0
09. \*/
10. public class ComparetorByNumber implements Comparator {
11. public int compare(Object o1, Object o2) {
12. Student s1=(Student)o1;
13. Student s2=(Student)o2;
14. //compare by number
15. int result=s1.getNumber() &gt; s2.getNumber() ? 1 :(s1.getNumber() == s2.getNumber() ? 0 : -1);
16. //if number is equal, then compare by name
17. if (result==0){
18. int compareByName=s1.getName().compareTo(s2.getName());
19. if(compareByName&gt;0)
20. result=1;
21. else if(compareByName==0)
22. result=0;
23. else
24. result=-1;
25. } //end if
26. return (-result); //如果是result,则a&gt;b比较结果后排序是ba，-result代表倒序排序
27. }
28. }&lt;/span&gt;

 

优先队列的使用

 

**\[java]** [view plain](http://blog.csdn.net/yangzhongblog/article/details/8607632 "view plain")[copy](http://blog.csdn.net/yangzhongblog/article/details/8607632 "copy")

 

01. &lt;span style="font-size:18px;"&gt;package zyang.priorityQueue;
02. import java.util.PriorityQueue;
03. /\**
04. * Fuction:
05. \*
06. * @author   yangzhong  E-mail:yangzhonglive@gmail.com
07. * @version  2013-2-24 下午8:15:39
08. * @since    1.0
09. \*/
10. public class PriorityQueueApp {
11. /\**
12. * @param args
13. \*/
14. public static void main(String\[] args) {
15. PriorityQueue&lt;Student&gt; priorityQueue=new PriorityQueue&lt;Student&gt;(3,new ComparetorByNumber());
16. Student\[] student={new Student(3,"wangwu"),new Student(2,"lisi"),
17. new Student(5,"xiaowang"),new Student(8,"lihua")};
18. for(Student s: student){
19. priorityQueue.offer(s); //use offer() method to add elements to the PriorityQueue
20. }
21. System.out.println("size: " + priorityQueue.size()); //print size
22. System.out.println("peek: " + priorityQueue.peek()); //return highest priority element in the queue without removing it
23. System.out.println("size: " + priorityQueue.size()); //print size
24. System.out.println("poll: " + priorityQueue.poll()); //return highest priority element and removes it from the queue
25. System.out.println("size: " + priorityQueue.size()); //print size
26. while(!priorityQueue.isEmpty()) {
27. System.out.print(priorityQueue.poll() + " ");
28. }
29. System.out.println("  the end!");
30. }
31. }
32. &lt;/span&gt;

输出结果如下：

 

![](http://img.my.csdn.net/uploads/201302/24/1361717417_6009.jpg)