我想通过使用指定的值将对象添加到优先级队列 像这样
PriorityQueue<Edge> queue=new PriorityQueue<Edge>();
这是类Edge,我希望按重量排序优先级队列
public class Edge {
private int start,end;
private double weight;
public Edge(int s, int e,Double w){
start=s;
end=e;
weight=w;
}
public int getStart(){
return start;
}
public int getEnd(){
return end;
}
public double getWeight(){
return weight;
}
答案 0 :(得分:4)
您应该通过指定应如何比较其元素来创建优先级队列。这是通过为Comparator
类传递匿名Edge
来完成的:
PriorityQueue<Edge> queue=new PriorityQueue<Edge>(10, new Comparator<Edge>() {
public int compare(Edge edge1, Edge edge2) {
if (edge1.getWeight() < edge2.getWeight()) return -1;
if (edge1.getWeight() > edge2.getWeight()) return 1;
return 0;
}
});
根据您的排序顺序,您可能需要切换-1
和1
的回报。
答案 1 :(得分:0)
您可以创建一个优先级队列和一个比较边缘的Checker(自定义)类。像这样:
class Checker implements Comparator<Edge>
{
public int compare(Edge ob1, Edge ob2)
{
if (ob1.getWeight() > ob2.getWeight()) return 1;
else return -1;
}
}
//Declared priority queue
PriorityQueue<Edge> queue=new PriorityQueue<Edge>(5, new Checker());
答案 2 :(得分:0)
Java 8:
PriorityQueue<Edge> queue = new PriorityQueue<>((edge1, edge2) -> {
if (edge1.getWeight() < edge2.getWeight()) {
return -1;
}
if (edge1.getWeight() > edge2.getWeight()) {
return 1;
}
return 0;
});