本文介绍了PriorityQueue 在添加时未排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个优先队列,我在其中添加了一个节点对象,节点应该按它们包含的值排序.出于某种原因,优先级队列不会在添加时对节点进行排序.如果有人能看到这里有什么问题或有任何指导,我很感激.下面是一个简单的例子:

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 不提供这种行为,因为它是作为优先级堆而不是排序列表实现的.来自 javadoc:

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:

方法 iterator() 中提供的 Iterator 不保证以任何特定顺序遍历优先级队列的元素.如果您需要有序遍历,请考虑使用 Arrays.sort(pq.toArray()).

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 在添加时未排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 01:43