我正在尝试创建一个优先级队列,其中键将为tatre()= getCost() getTax()。我将优先的队列设置为这样:
PriorityQueue<Node> pq = new PriorityQueue<Node>(50);
我一直在查看有关优先队列的内容,并且我读到了有关比较器,但我仍然迷失了整个事情。如何使用下面的方法为我的优先级队列设置钥匙?
获得总计的方法:
public int compareTo(Node y){
if (getCost() + getTax() > y.getCost() + y.getTax())
return 1;
else if (getCost() + getTax() < y.getCost() + y.getTax())
return -1;
return 0;
}
初始化PriorityQueue
时可以直接传递比较器:
PriorityQueue<Node> pq = new PriorityQueue<Node>(50, (x, y) -> {
if (x.getCost() + x.getTax() > y.getCost() + y.getTax())
return 1;
else if (x.getCost() + x.getTax() < y.getCost() + y.getTax())
return -1;
return 0;
});
我会去这个解决方案:
PriorityQueue<Node> pq = new PriorityQueue<>(50, Node::compareTo);
PriortityQueue构造函数可以采用初始容量和比较对象。由于Java 8,因此可以用lambda或方法引用(如我的示例中)替换。
当对象实现Comparable
接口时,PriorityQueue
将自动使用对象的"自然排序"。它将使用Node
类的compareTo()
方法选择下一个Node
对象。您无需提供其他Comparator
类,该类比较您的Node
对象。
public Node implements Comparable<Node>
{
// [...]
@Override
public int compareTo(Node y){
if (getCost() + getTax() > y.getCost() + y.getTax())
return 1;
else if (getCost() + getTax() < y.getCost() + y.getTax())
return -1;
return 0;
}
}
然后简单地创建使用PriorityQueue
对象。
PriorityQueue<Node> queue = new PriorityQueue<Node>();
queue.add(node1);
queue.add(node2);
queue.add(node3);
Node next = queue.poll();