PriorityQueue<Integer>queue=newPriorityQueue<>();queue.offer(5);queue.offer(8);queue.offer(1);System.out.println(queue.poll());// 输出 1 使用Comparator排序 代码语言:javascript 代码运行次数:0 运行 AI代码解释 PriorityQueue<String>queueWithComparator=newPriorityQueue<>(newComparator<String>(){@Overri...
intsize=priorityQueue.size(); System.out.println("Queue size: "+ size); 遍历队列中的元素。 for(Integerelement: priorityQueue) {System.out.println(element); } 注意:PriorityQueue是无序的,所以输出的元素顺序可能与添加时的顺序不同。如果你需要按照插入顺序遍历元素,可以考虑使用LinkedBlockingQueue代替。
先看一个例子吧: importjava.util.Comparator;importjava.util.PriorityQueue;importjava.util.Queue;importjava.util.Random;publicclassPriorityQueueExample{publicstaticvoidmain(String[]args){Queue<Integer>integerPriorityQueue=newPriorityQueue<>(7);for(inti=0;i<7;i++){integerPriorityQueue.add(i);}for(inti=...
};publicstaticvoidmain(String[] args) {//不用比较器,默认升序排列Queue<Integer> q =newPriorityQueue<>(); q.add(3); q.add(2); q.add(4);while(!q.isEmpty()) { System.out.print(q.poll()+" "); }/*** 输出结果 * 2 3 4*///使用自定义比较器,降序排列Queue<Integer> qq =newPri...
PriorityQueue<Integer> que=newPriorityQueue<Integer>(newComparator<Integer>() {publicintcompare(Integer o1, Integer o2){returno2-o1; } });for(inte:a) { que.add(e); }for(inte:que) { System.out.print(e+" "); } System.out.println();while(!que.isEmpty()) {inte=que.remove(); ...
Queue<Integer> priorityQueue = new PriorityQueue<>(); 1. Integer本身也实现了Comparable接口,比较方法如下 public static int compare(int x, int y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); } 1. 2. 3. 因此上面的priorityQueue中数值小的优先度更高 ...
Queue<Integer> queue = new PriorityQueue<>(Collections.reverseOrder()); 1. 优先级队列中最重要的两个操作是入队和出队,下面就从源码的角度来简要分析一下。 二、入队 PriorityQueue 的 add 和 offer 方法都是入队,主要的代码是这样的: /** * Inserts the specified element into this priority queue. ...
public boolean add(E e) { if (offer(e)) return true; else throw new IllegalStateException("Queue full"); } 3.1.3 使用方式 自然排序 public static void main(String[] args) { PriorityQueue<Integer> queue = new PriorityQueue<>(); System.out.println("插入的数据"); //随机添加两位数 for...
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 */ } 2.队列保存的是⾃定义类 //矩形类 class Node{ public Node(int chang,int kuan){ this.chang=chang;this....
PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder()); 这里我们通过Comparator.reverseOrder()方法创建了一个比较器,它根据降序排列元素。通过将该比较器作为参数传递给PriorityQueue的构造函数,我们可以创建一个按照降序排序的优先队列。 7.总结 PriorityQueue是一个非常有用的数据结构,它允许我们...