java priorityqueue
java priorityqueue是怎样的呢?下面就让我们一起来了解一下吧:
java中的priorityqueue一般也就是代表优先队列。
这是属于Queue接口的实现,能够对其中元素进行排序,还能放基本数据类型的包装类或是自定义的类,而对于基本数据类型的包装类,优先队列中元素一般是默认排列顺序为升序排列的。
参考范例:
队列保存的是基本数据类型的包装类,具体代码为:
//自定义比较器,降序排列
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(3);
q.add(2);
q.add(4);
while(!q.isEmpty())
{
System.out.print(q.poll()+" ");
}
/**
* 输出结果
* 2 3 4
*/
//使用自定义比较器,降序排列
Queue<Integer> qq = new PriorityQueue<>(cmp);
qq.add(3);
qq.add(2);
qq.add(4);
while(!qq.isEmpty())
{
System.out.print(qq.poll()+" ");
}
/**
* 输出结果
* 4 3 2
*/
}
队列保存的是自定义类,具体代码为:
//矩形类
class Node{
public Node(int chang,int kuan)
{
this.chang=chang;
this.kuan=kuan;
}
int chang;
int kuan;
}
public class Test {
//自定义比较类,先比较长,长升序排列,若长相等再比较宽,宽降序
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
*/
}
}
-
为什么不建议买混合动力汽车,混合动力汽车的优点
油电混合汽车还有一个非常大的缺点是不保值,虽说现如今油电混合汽车在市场上越来越多。可是和汽油车相比较,油电混合汽车的总数可谓是小巫见大巫。现阶段顾客也是以选购汽油车为重,因而如...
问答查看全文>> -
歌诗图新款与老款区别是什么?
歌诗图新款与老款的区别:1、小歌可以说在2016款上并不像14款上市时候变化很大;2、16款跟14款基本上没有什么大的改变,外前镀银的横梁稍微变窄了、颜色多了一款琥珀金,别的没...
问答查看全文>> -
驻车制动器故障打不着火怎么办?
驻车制动器故障打不着火,可引发制动系统故障的部件或原因:1、可能是制动蹄片故障,磨损异常或不规则磨损,制动液缺少或是质量不达标(如气阻)等;2、漏油(制动液 ),制动碟故障,磨...
问答查看全文>> -
雪佛兰科帕奇机油型号,科帕奇用5W30还是5W40
雪佛兰科帕奇机油使用雪佛兰专用机油sm/gf-4 5W-30的全合成机油,这个机油的性能算是非常棒的了,不过可惜的是还是5000公里保养一次,一般加机油是加4.5L。汽车润滑油...
问答查看全文>>
推荐
- 1描写情绪低落的句子 心情极差情绪低落语句404
- 2多肉掉叶子是怎么回事355
- 3原神提瓦特哪里有浪船354
- 4红米K40pro+和荣耀50参数对比_哪个好317
- 5迈腾自动挡车启动步骤121
- 6燃油汽车构造包括哪些组成部分320
- 7linux重启ssh服务命令463
- 8电脑删除文件显示在另一个程序打开怎么办413