PriorityQueue
是基于priorty
堆的未绑定优先级队列。 PriorityQueue
中元素的顺序取决于使用的构造函数的类型。 默认情况下,PriorityQueue
按自然顺序排序。 可以在实例化优先级队列时提供比较器。
PrioryQueue的基本操作是:
offer()
和add()
– 将指定的元素插入优先级队列。poll()
和remove()
– 检索并删除优先级队列的头部。peek()
和element()
– 检索但不删除优先级队列的头部。
如果任何条件失败,add()
,remove()
和element()
方法抛出异常。
如果任何条件失败,provide()
,poll()
和peek()
方法返回特殊值(null
或false
,具体取决于操作)。
在本节中,我们将展示人员优先队列的示例。
文件:Person.java –
package com.yiibai.tutorial; /** * @author yiibai * */ public class Person{ private int id; private String name; private int age; public Person(int idString nameint age) { this.setId(id); this.setName(name); this.setAge(age); } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return "("+id+""+name+""+age+")"; } }
文件:PersonComparator.java – 此类将根据人的年龄确定队列的优先级。
package com.yiibai.tutorial; import java.util.Comparator; /** * @author yiibai * */ public class PersonComparator implements Comparator<Person>{ @Override public int compare(Person o1 Person o2) { return (o2.getAge()-o1.getAge()); } }
文件:PriorityQueueExample.java –
package com.yiibai.tutorial; import java.util.PriorityQueue; import java.util.Queue; /** * @author yiibai * */ public class PriorityQueueExample { public static void main(String[] args) { Queue<Person> queue=new PriorityQueue<>(new PersonComparator()); /*Add elements to queue*/ queue.offer(new Person(1"Sunil"25)); queue.offer(new Person(2"John"20)); queue.offer(new Person(3"Jack"30)); queue.offer(new Person(4"Mack"40)); queue.offer(new Person(5"Tom"15)); System.out.println("Elements in queue: "+queue); /*Remove element from the queue*/ Person personEle=queue.poll(); System.out.println("Removed element: "+personEle.toString()); System.out.println("Elements in queue after poll: "+queue); /*Get first element from the queue*/ Person person=queue.peek(); System.out.println("Returned element: "+person.toString()); System.out.println("Elements in queue after peek: "+queue); } }
执行上面示例代码,得到以下结果:
Elements in queue: [(4Mack40) (3Jack30) (1Sunil25) (2John20) (5Tom15)] Removed element: (4Mack40) Elements in queue after poll: [(3Jack30) (2John20) (1Sunil25) (5Tom15)] Returned element: (3Jack30) Elements in queue after peek: [(3Jack30) (2John20) (1Sunil25) (5Tom15)]
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264136.html