目录
一.导语
Java集合框架中提供了PriorityQueue和PriorityBlockingQueue两种类型的优先级队列,PriorityQueue是线程不安全的,PriorityBlockingQueue是线程安全的
通过观察源码:
使用必须导包!
堆有很多方法的,接下来我们将学习堆!
PriorityQueue中放置的元素必须要能够比较大小,不能插入无法比较大小的对象,否则会抛出ClassCastException异常
不能插入null对象,否则会抛出NullPointerException
没有容量限制,可以插入任意多个元素,其内部可以自动扩容
二.offer,poll,peak等 默认是小根堆!
offer插入的对象,必须是可以比较的否则会抛异常!
这种情况必须Student类必须可以比较
究其本质,我们来学习源码:
第一行,看其源码中的构造方法:
该构造方法作用: 调用有俩个参数的构造方法
第二步:offer
第三步:第二次offer
如果我们想使用小根堆来实现,该怎么办呢?
如果是在Student类内改写比较容易!
将Student类的compareTo方法改写一下,但如果是Interger包装类型呢?
这里需要传入一个比较器!
比较器:
class Intcmp implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}
main函数
public static void main(String[] args) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(11,new Intcmp());
priorityQueue.offer(12);
priorityQueue.offer(3);
System.out.println(priorityQueue.poll());
System.out.println(priorityQueue.poll());
}
比较器也可以使用匿名内部类来传入
public static void main(String[] args) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(11,new Comparator<Integer>(){
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
});
priorityQueue.offer(12);
priorityQueue.offer(3);
System.out.println(priorityQueue.poll());
System.out.println(priorityQueue.poll());
}