java中PriorityQueue<Node>
时间: 2024-06-14 16:06:09 浏览: 11
在Java中,PriorityQueue是一个优先级队列的实现类。它可以用来存储具有优先级的元素,并根据元素的优先级进行排序。在PriorityQueue中,元素被称为节点(Node)。
下面是一个示例代码,演示了如何使用PriorityQueue存储Node对象,并根据节点的优先级进行排序:
```java
import java.util.PriorityQueue;
public class Node implements Comparable<Node> {
private int priority;
public Node(int priority) {
this.priority = priority;
}
public int getPriority() {
return priority;
}
@Override
public int compareTo(Node other) {
return Integer.compare(this.priority, other.priority);
}
public static void main(String[] args) {
PriorityQueue<Node> queue = new PriorityQueue<>();
queue.add(new Node(3));
queue.add(new Node(1));
queue.add(new Node(2));
while (!queue.isEmpty()) {
Node node = queue.poll();
System.out.println("Node priority: " + node.getPriority());
}
}
}
```
在上面的代码中,我们定义了一个Node类,它具有一个priority属性和一个实现了Comparable接口的compareTo方法。compareTo方法用于比较节点的优先级。
在main方法中,我们创建了一个PriorityQueue对象,并向其中添加了三个Node对象。然后,我们使用poll方法从队列中取出节点,并打印节点的优先级。
运行上述代码,输出将是:
```
Node priority: 1
Node priority: 2
Node priority: 3
```
这表明节点按照优先级从小到大的顺序被取出。
相关推荐
![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)
![](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)