PriorityQueue not sorting on add

和自甴很熟 提交于 2019-11-26 06:44:40

问题


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 compareTo method:

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

回答1:


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:

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()).

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.




回答2:


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

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.



来源:https://stackoverflow.com/questions/5695017/priorityqueue-not-sorting-on-add

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!