priorityqueue重写compare
时间: 2023-10-19 09:25:21 浏览: 54
对于重写 `PriorityQueue` 的 `compare` 方法,你需要实现 `Comparator` 接口并重写其 `compare` 方法。以下是一个示例:
```java
import java.util.Comparator;
import java.util.PriorityQueue;
public class Example {
public static void main(String[] args) {
// 创建一个自定义比较器对象
CustomComparator customComparator = new CustomComparator();
// 使用自定义比较器创建一个优先队列
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(customComparator);
// 添加元素到优先队列
priorityQueue.offer(3);
priorityQueue.offer(1);
priorityQueue.offer(2);
// 输出队列中的元素
while (!priorityQueue.isEmpty()) {
System.out.println(priorityQueue.poll());
}
}
}
// 自定义比较器类
class CustomComparator implements Comparator<Integer> {
@Override
public int compare(Integer num1, Integer num2) {
// 可根据自己的需求编写比较逻辑
// 这里示例按照数字大小进行降序排序
return num2 - num1;
}
}
```
在上述示例中,我们创建了一个自定义的比较器 `CustomComparator`,并通过 `PriorityQueue` 的构造函数将其传入。在 `CustomComparator` 中,我们重写了 `compare` 方法,按照数字大小进行降序排序。可以根据自己的需求修改比较逻辑。最后,我们将元素添加到优先队列中,并使用 `poll` 方法按照定义的比较逻辑输出队列中的元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)