In Java if we want to sort based on second item in PriorityQueue using Comparable interface The Code will be like this:
import java.util.*;
public class Main{
public static class Pair implements Comparable{
int node;
int weight;
public Pair(int node,int weight){
this.node = node;
this.weight = weight;
}
@Override
public int compareTo(Object o) {
return this.weight - ((Pair)o).weight;
}
}
public static void main(String [] args){
PriorityQueue<Pair> pq = new PriorityQueue<Pair>();
pq.add(new Pair(2,3));
pq.add(new Pair(2,3));
}
}
But, if the weight data type will be long or double how to handle for sorting priorityQueue regarding this case?
Need Help! Thanks in advance.
public static class Pair implements Comparable<Pair>{
int node;
Double weight;
public Pair(int node,double weight){
this.node = node;
this.weight = weight;
}
@Override
public int compareTo(Pair o) {
return this.weight.compareTo(o.weight);
}
}