PriorityQueue用法
作者:互联网
PriorityQueue优先队列
PriorityQueue<Integer> queue=new PriorityQueue<>(); //默认从小到大
PriorityQueue<Integer> queue=new PriorityQueue<>( (a,b)->(b-a)); //从大到小
PriorityQueue<int[]> queue=new PriorityQueue<>((a,b)->(a[0]-b[0])); //自定义排序 数组的第一个数字
自定义排序
第一种写法:
类不实现Comparable
lamda表达式定义compator
PriorityQueue<Eage> queue=new PriorityQueue<>(
(a,b)->(a.weight-b.weight>0?-1:1) //lamda表达式,compartor如果顺序对返回1,如果顺序不对返回-1
);
class Eage{
int node;
double weight;
Eage(int x,double y){
this.node=x;
this.weight=y;
}
}
第二种写法:
类不实现Comparable
自定义新的compator
PriorityQueue<Eage> queue=new PriorityQueue<>(
new Comparator<Eage>() {
@Override
public int compare(Eage o1, Eage o2) {
return o1.weight-o2.weight>0?-1:1;
}
}
);
class Eage{
int node;
double weight;
Eage(int x,double y){
this.node=x;
this.weight=y;
}
}
第三种写法:
类实现Comparable
优先队列可以不定义compator
PriorityQueue<Eage> queue=new PriorityQueue<>();
class Eage implements Comparable<Eage>{
int start;
int end;
double weight;
public Eage(int x,int y,double z){
this.start=x;
this.end=y;
this.weight=z;
}
public int compareTo(Eage eage){
return this.weight-eage.weight>0?-1:1;
}
}
标签:weight,Eage,int,double,用法,PriorityQueue,new 来源: https://www.cnblogs.com/benbicao/p/15818002.html