Tre*_*ski 25 java sorting priority-queue
我有一个优先级队列,我在其中添加一个Node对象,其中节点应按其包含的值排序.由于某种原因,优先级队列不会对添加的节点进行排序.如果有人可以看到这个问题或有任何指导,我很感激.这是一个简短的例子:
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));
}
Run Code Online (Sandbox Code Playgroud)
这是节点的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;
}
Run Code Online (Sandbox Code Playgroud)
谁在寻找如何按照顺序迭代队列,这可以通过使用poll或remove来实现。
while (!queue.isEmpty())
System.out.println(queue.poll());
while (!queue.isEmpty())
System.out.println(queue.remove());
Run Code Online (Sandbox Code Playgroud)
poll()
和之间的唯一区别remove()
是 poll 在为空时返回 null ,而 remove 抛出 a NoSuchElementException
。