java PriorityQueue 在添加时未排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5695017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:21:44  来源:igfitidea点击:

PriorityQueue not sorting on add

javasortingpriority-queue

提问by Trevor Arjeski

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));
        }

here is the node's compareTomethod:

这是节点的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;
}

回答by axtavt

I guess you expect PriorityQueueto return elements in particular order when you iterate it. However, PriorityQueuedoesn't provide such a behaviour, because it's implemented as a priority heap rather than sorted list. From javadoc:

我猜您希望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()).

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

The only guarantee provided by PriorityQueueis that poll(), peek(), etc return the least element. If you need ordered iteration of elements, use some other collection such as TreeSet.

所提供的唯一保证PriorityQueuepoll()peek()等返回的最小元素。如果您需要元素的有序迭代,请使用其他一些集合,例如TreeSet.

回答by Jose Da Silva

Who is looking for how to iterate the queue following the order, this can be achieved by using pollor remove.

谁在寻找如何按照顺序迭代队列,这可以通过使用pollremove来实现。

while (!queue.isEmpty())
    System.out.println(queue.poll());

while (!queue.isEmpty())
    System.out.println(queue.remove());

The only diference between poll()and remove(), is that poll returns null when is empty and remove throws a NoSuchElementException.

poll()和之间的唯一区别remove()是 poll 在为空时返回 null ,而 remove 抛出 a NoSuchElementException