Search code examples
javapriority-queue

sort priority queue of objects by specified value


i want to add objects to priority queue by using specified value like this

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

this is class Edge which i want to sort in priority queue by its weight

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

Solution

  • You should create your priority Queue a little bit different by specifying how its elements should be compared. That is done by passing an anonymous Comparator for the Edge class:

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

    Maybe you will have to switch the returns of -1 and 1 depending on your sorting order.