我创建了一个 Node 类:
public class Node {
int vertex;
double latency;
Node predecessor;}
public double getLatency()
{
return latency;
}
我想创建一个优先级队列,按延迟从最小到最大对节点进行排序。经过研究,我认为我需要重写比较器?
PriorityQueue<Node> pqueue = new PriorityQueue<Node>(numVertices, new Comparator<Node>({
@Override
???
}
}
我不太确定如何覆盖它。
最佳答案
您实际上只需要比较两种延迟。这意味着重写 Comparator 类的方法 compare
来比较两个输入 Node
的延迟:
PriorityQueue<Node> pqueue = new PriorityQueue<Node>(numVertices, new Comparator<Node>({
@Override
public int compare(Node a, Node b) {
return Integer.compare(a.getLatency(), b.getLatency());
}
}
但是这仅适用于 Java 7,对于其他版本:
new Integer(a.getLatency()).compareTo(new Integer(b.getLatency()));
如果您不想创建新对象,则像往常一样比较两个 int
关于java - 如何创建根据类的某些属性排序的优先级队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15646207/