问题描述
我有一个优先级队列,我在其中添加一个Node对象,其中节点应按其包含的值进行排序。出于某种原因,优先级队列不会对添加的节点进行排序。如果有人可以看到这个问题或有任何指导,我很感激。这是一个简短的例子:
I have a Priority Queue in which I add a Node object to, where the Nodes should be sorted by a value that they contain. For some reason, the priority queue will not sort the Nodes on add. If anyone can see something wrong with this or has any guidance, I appreciate it. Here is a brief example:
PriorityQueue<Node> PQ = new PriorityQueue<Node>();
//for each entry create a node and add it to the PriorityQueue
for(Entry<Character,Integer> entry : entries){
PQ.add(new Node(entry.getKey(),entry.getValue(), true));
}
这里是节点的 compareTo
方法:
@Override
public int compareTo(Node n) {
if(n.frequency.intValue() > this.frequency.intValue()) return -1;
else if(n.frequency.intValue() == this.frequency.intValue()) return 0;
else return 1;
}
推荐答案
我猜您期望 PriorityQueue
在迭代时以特定顺序返回元素。但是, PriorityQueue
不提供这样的行为,因为它是作为优先级堆而不是排序列表实现的。来自:
I guess you expect PriorityQueue
to return elements in particular order when you iterate it. However, PriorityQueue
doesn't provide such a behaviour, because it's implemented as a priority heap rather than sorted list. From javadoc:
PriorityQueue
提供的唯一保证是 poll()
, peek()
等返回最少的元素。如果您需要对元素进行有序迭代,请使用其他集合,例如 TreeSet
。
The only guarantee provided by PriorityQueue
is that poll()
, peek()
, etc return the least element. If you need ordered iteration of elements, use some other collection such as TreeSet
.
这篇关于PriorityQueue没有在添加上排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!