PriorityQueue

来源:互联网 发布:无敌淘宝网 编辑:程序博客网 时间:2024/04/30 01:23

以前数据结构课学过队列,知道了队列是先进先出的数据结构,就像排队,先到先得。然而在最近,我却看到了一个“尊老爱幼”的队列,他会把位置让给优先权最高的元素。


下面先做个例子:

package org.jian.test;import java.util.LinkedList;import java.util.PriorityQueue;import java.util.Queue;public class PriorityQueueTest {public static void main(String[] args) {Queue<Person> priorityQueue = new PriorityQueue<Person>() ;Queue<Person> queue = new LinkedList<Person>() ;Person p1 = new Person("jian" , 20) ;Person p2 = new Person("hundun" , 23) ;Person p3 = new Person("martin" , 17) ;Person p4 = new Person("wu" , 33) ;Person p5 = new Person("openjdk8" , 32) ;Person p6 = new Person("dou" , 41) ;Person p7 = new Person("tao" , 14) ;//优先队列入队priorityQueue.offer(p1) ;priorityQueue.offer(p2) ;priorityQueue.offer(p3) ;priorityQueue.offer(p4) ;priorityQueue.offer(p5) ;priorityQueue.offer(p6) ;priorityQueue.offer(p7) ;//-----------------------//普通队列入队queue.offer(p1) ;queue.offer(p2) ;queue.offer(p3) ;queue.offer(p4) ;queue.offer(p5) ;queue.offer(p6) ;queue.offer(p7) ;System.out.println("普通队列测试--------------------------------------------------------------");Person person = null ;while((person=queue.poll())!=null){System.out.println("姓名:"+person.getName()+",年龄为:"+person.getAge());}System.out.println("优先队列测试--------------------------------------------------------------");while((person=priorityQueue.poll())!=null){System.out.println("姓名:"+person.getName()+",年龄为:"+person.getAge());}}}/** * 继承了Comparable接口 * @author Administrator * */class Person implements Comparable{   private String name ;private int age ;public Person(String name, int age) {this.name = name;this.age = age;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}/** * 通过年龄的大小进行比较 */@Overridepublic int compareTo(Object o) {Person p = (Person)o ;if(this.age>p.age){return 1 ;}else if(this.age==p.age){return 0 ;}else {return -1 ;}}}

运行结果:


+--------------------------------------------------------------------------------------------------------

普通队列测试--------------------------------------------------------------
姓名:jian,年龄为:20
姓名:hundun,年龄为:23
姓名:martin,年龄为:17
姓名:wu,年龄为:33
姓名:openjdk8,年龄为:32
姓名:dou,年龄为:41
姓名:tao,年龄为:14
优先队列测试--------------------------------------------------------------
姓名:tao,年龄为:14
姓名:martin,年龄为:17
姓名:jian,年龄为:20
姓名:hundun,年龄为:23
姓名:openjdk8,年龄为:32
姓名:wu,年龄为:33
姓名:dou,年龄为:41

+--------------------------------------------------------------------------------------------------------

显然我们看到了普通队列是按“先到先得排列的”,而优先队列则是按对象的“大小”进行排列的,真可谓“尊老爱幼”。


0 0
原创粉丝点击