我有一个优先队列,我在其中添加了一个节点对象,节点应该按它们包含的值排序。由于某种原因,优先级队列不会在添加时对节点进行排序。如果有人对此有任何问题或有任何指导,我将不胜感激。下面是一个简单的例子:
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
不提供这样的行为,因为它是作为优先级堆而不是排序列表实现的。来自 javadoc :
The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).
PriorityQueue
提供的唯一保证是 poll()
、peek()
等返回最少的元素。如果您需要元素的有序迭代,请使用其他集合,例如 TreeSet
。
关于java - PriorityQueue 未在添加时排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5695017/