PriorityQueue没有在添加上排序
我有一个优先级队列,我在其中添加一个Node对象,其中节点应按其包含的值进行排序。 出于某种原因,优先级队列不会对添加的节点进行排序。 如果有人可以看到这个问题或有任何指导,我很感激。 这是一个简短的例子:
PriorityQueue PQ = new PriorityQueue(); //for each entry create a node and add it to the PriorityQueue for(Entry 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 :
方法iterator()中提供的迭代器不保证以任何特定顺序遍历优先级队列的元素。 如果需要有序遍历,请考虑使用Arrays.sort(pq.toArray())。
PriorityQueue
提供的唯一保证是poll()
, peek()
等返回最小元素。 如果需要对元素进行有序迭代,请使用其他一些集合,例如TreeSet
。
谁在寻找如何按顺序迭代队列,这可以通过使用poll或remove来实现。
while (!queue.isEmpty()) System.out.println(queue.poll()); while (!queue.isEmpty()) System.out.println(queue.remove());
poll()
和remove()
之间的唯一区别是,当为空时poll返回null并且remove抛出NoSuchElementException
。