Java队列容器-优先队列PriorityQueue

开发者 2024-9-4 01:39:25 92 0 来自 中国
一、优先队列概述
  优先队列PriorityQueue是Queue接口的实现,可以对其中元素举行排序,
可以放根本数据范例的包装类(如:Integer,Long等)或自界说的类
   对于根本数据范例的包装器类,优先队列中元素默认分列序次是升序分列但对于本身界说的类来说,须要本身界说比力器
二、常用方法
peek()//返回队首元素
poll()//返回队首元素,队首元素出队列 add()//添加元素 size()//返回队列元素个数 isEmpty()//判定队列是否为空,为空返回true,不空返回false三、优先队列的使用
1.队列生存的是根本数据范例的包装类
//自界说比力器,降序分列
static Comparator cmp =new Comparator() {
  public int compare(Integer e1, Integer e2) {    return e2 - e1;  }};public static void main(String[] args) {
    //不消比力器,默认升序分列    Queue q =new PriorityQueue<>();    q.add(3);    q.add(2);    q.add(4);    while(!q.isEmpty()){        System.out.print(q.poll()+" ");    }    /**             * 输出效果 2 3 4    */   //使用自界说比力器,降序分列   Queue qq =new PriorityQueue<>(cmp);    qq.add(3);    qq.add(2);    qq.add(4);    while(!qq.isEmpty()) {        System.out.print(qq.poll()+" ");    }    /**           * 输出效果    * 4 3 2    */}2.队列生存的是自界说类
//矩形类class Node{
publicNode(intchang,int kuan){    this.chang=chang;    this.kuan=kuan;}int chang;int kuan;}
public class Test {
//自界说比力类,先比力长,长升序分列,若长相称再比力宽,宽降序static     Comparator cNode=new Comparator() {
    publicint compare(Node o1, Node o2) {        if(o1.chang!=o2.chang)            returno1.chang-o2.chang;        else           return o2.kuan-o1.kuan;    }};public static void main(String[] args) {    Queue q=new PriorityQueue<>(cNode);    Node n1=new Node(1, 2);    Node n2=new Node(2, 5);    Node n3=new Node(2, 3);    Node n4=new Node(1, 2);    q.add(n1);    q.add(n2);    q.add(n3);    Node n;    while(!q.isEmpty()) {        n=q.poll();        System.out.println("长: "+n.chang+" 宽:" +n.kuan);    }}
}
3.优先队列遍历
  PriorityQueue的iterator()不包管以任何特定序次遍历队列元素。
若想按特定序次遍历,先将队列转成数组,然后排序遍历
示例
Queue q =new PriorityQueue<>(cmp);
    int[] nums= {2,5,3,4,1,6};    for(int i:nums){        q.add(i);    }    Object[] nn=q.toArray();    Arrays.sort(nn);    for(inti=nn.length-1;i>=0;i--)        System.out.print((int)nn+" ");4.比力器生降序分析
Comparator cmp =newComparator() {
    publicint compare(Object o1, Object o2) {        //升序returno1-o2;        //降序returno2-o1;    }};
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-19 06:19, Processed in 0.134614 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表