按指定值排序对象的优先级队列

sort priority queue of objects by specified value

我想使用指定值将对象添加到优先级队列 像这样

PriorityQueue<Edge> queue=new PriorityQueue<Edge>();

这是 class 我想按其权重在优先级队列中排序的边

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;
}

您应该通过指定如何比较其元素来创建稍微不同的优先级队列。这是通过为 Edge class:

传递匿名 Comparator 来完成的
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;
    }
});

也许您需要根据您的排序顺序切换 -11 的 returns。

您可以创建优先级队列和检查器(自定义)class 来比较边。像这样:

  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());

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;
});