在Java库中PriorityQueue默认是最小堆,而在使用中根据实际情况可能建立最大堆,因此要通过comparator接口重写compare方法。
1 创建类
手动定义一个比较器对象改变建堆的方式,借助比较器对象,在优先队列中传入比较器。
import java.util.Comparator;
import java.util.PriorityQueue;
public class Test {
static class MyComp implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>(new MyComp());
queue.offer(9);
queue.offer(5);
queue.offer(2);
queue.offer(0);
queue.offer(3);
queue.offer(4);
queue.offer(7);
while (!queue.isEmpty()){
Integer cur = queue.poll();
System.out.print(cur+" ");
}
}
}
9 7 5 4 3 2 0
2 匿名内部类
传入一个不知类名的比较器对象,不知道类名,但是知道类实现了comparator接口
public class Test {
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
queue.offer(9);
queue.offer(5);
queue.offer(2);
queue.offer(0);
queue.offer(3);
queue.offer(4);
queue.offer(7);
while (!queue.isEmpty()){
Integer cur = queue.poll();
System.out.print(cur+" ");
}
}
}
9 7 5 4 3 2 0
3 lambda表达式
import java.util.PriorityQueue;
public class Test {
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>((o1,o2) -> o2 -o1);
queue.offer(9);
queue.offer(5);
queue.offer(2);
queue.offer(0);
queue.offer(3);
queue.offer(4);
queue.offer(7);
while (!queue.isEmpty()){
Integer cur = queue.poll();
System.out.print(cur+" ");
}
}
}
9 7 5 4 3 2 0