Java优先队列PriorityQueue使用详解

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

优先队列的使用

1.队列保存的是基本数据类型的包装类

//自定义比较器,降序排列
	static Comparator<Integer> cmp = new Comparator<Integer>() {
	      public int compare(Integer e1, Integer e2) {
	        return e2 - e1;  //降序
	      }
	    };
	public static void main(String[] args) {
	        //不用比较器,默认升序排列
	        Queue<Integer> q = new PriorityQueue<>();
	        q.add(8);
	        q.add(5);
	        q.add(13);
	        q.add(2);
	        System.out.println("**********不使用比较器********************");
	        while(!q.isEmpty())
	        {
	            System.out.print(q.poll()+" ");
	        }
	        System.out.println();
	        System.out.println("**********使用比较器********************");
	        //使用自定义比较器,降序排列
	        Queue qq = new PriorityQueue(cmp);
	        qq.add(8);
	        qq.add(5);
	        qq.add(13);
	        qq.add(2);
	        while(!qq.isEmpty())
	        {
	            System.out.print(qq.poll()+" ");
	        }
	}
**********不使用比较器********************
2 5 8 13 
**********使用比较器********************
13 8 5 2 

2.队列保存的是自定义类

	    //自定义比较类,先比较长,长升序排列,若长相等再比较宽,宽降序
	    static Comparator<Node> cNode=new Comparator<Node>() {
	        public int compare(Node o1, Node o2) {
	            if(o1.chang!=o2.chang)
	                return o1.chang-o2.chang;
	            else
	                return o2.kuan-o1.kuan;
	        }
	        
	    };
	    public static void main(String[] args) {
	    	Queue<Node> 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);
	        }
	    }
	
: 1 宽:2: 2 宽:5: 2 宽:3

3.优先队列遍历
PriorityQueue的iterator()不保证以任何特定顺序遍历队列元素。

若想按特定顺序遍历,先将队列转成数组,然后排序遍历

Queue<Integer> 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(int i=nn.length-1;i>=0;i--)
            System.out.print((int)nn[i]+" ");
        /**
         * 输出结果
         * 6 5 4 3 2 1 
         */

4.比较器生降序说明

Comparator<Object> cmp = new Comparator<Object>() {
        public int compare(Object o1, Object o2) {
            //升序
            return o1-o2;
            //降序
            return o2-o1;
        }
    };

这是搬得大大的,网址如下:
https://blog.csdn.net/qq_22596931/article/details/110421457

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值