java优先队列代码
时间: 2023-12-25 12:29:17 浏览: 165
以下是Java中使用优先队列的示例代码:
```java
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String[] args) {
// 创建一个优先队列
PriorityQueue<Integer> pq = new PriorityQueue<>();
// 添加元素到优先队列
pq.offer(5);
pq.offer(2);
pq.offer(8);
pq.offer(1);
// 获取并移除队列中的最小元素
int minElement = pq.poll();
System.out.println("Min element: " + minElement); // 输出:Min element: 1
// 获取队列中的最小元素,但不移除
int peekElement = pq.peek();
System.out.println("Peek element: " + peekElement); // 输出:Peek element: 2
// 判断队列是否为空
boolean isEmpty = pq.isEmpty();
System.out.println("Is empty: " + isEmpty); // 输出:Is empty: false
// 获取队列的大小
int size = pq.size();
System.out.println("Size: " + size); // 输出:Size: 3
}
}
```
阅读全文
相关推荐
















