Java的优先队列PriorityQueue

一、概念
优先队列PriorityQueue是Queue接口的实现,可以对其中元素进行排序,可以放基本数据类型的包装类(如:Integer,Long等)或自定义的类。对于基本数据类型的包装器类,优先队列中元素默认排列顺序是升序排列。但对于自己定义的类来说,需要自己定义比较器。
二、常用基本方法

peek()//返回队首元素
poll()//队首元素出队并返回队首元素
add()//添加元素
size()//返回队列元素个数
isEmpty()//判断队列是否为空,空返回true,非空返回false;

三、优先队列的使用
1、不使用比较器,默认升序排列

Queue<Integer> q=new PriorityQueue<>();
q.add(1);
q.add(3);
q.add(2);
while(q.isEmpty()){
 System.out.print(q.poll()+" ");
}
//输出结果为
//1 2 3

2、使用比较器

Queue<Integer> p=new PriorityQueue<>((e1,e2)->e2-e1);
q.add(2);
q.add(1);
q.add(3);
while(q.isEmpty()){
 System.out.print(q.poll()+" ");
}
//输出结果为
//3 2 1
Queue<Integer> p=new PriorityQueue<>((e1,e2)->e2-e1);
//可以写为
Queue<Integer> p=new PriorityQueue<>(cmp);
static Comparator<Integer> cmp = new Comparator<Integer>() {
      public int compare(Integer e1, Integer e2) {
        return e2 - e1;//为降低//e1-e2为升序
      }
    };

3、实现其它功能比较

private int sum(arr){
 return arr[0]+arr[1];
}
public static void main(String[] args){
 Queue<int[]> p=new PriorityQueue<>((e1,e2)->sum(e2)-sum(e1));
 int[] a1={1,2};
 int[] a2={3,5};
 p.add(a1);
 p.add(a2);
 int[] b=p.poll();
 System.out.print(b[0]+" ");
 System.out.print(b[1]);
}
//输出结果为
//3 5
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值