Iterating through PriorityQueue doesn't yield ordered results

孤街浪徒 提交于 2019-12-02 08:08:05

问题


import java.util.*;
class Priority{  
public static void main(String args[]){  

PriorityQueue<String> queue=new PriorityQueue<String>();  
queue.add("Amit");  
queue.add("Vijay");  
queue.add("Karan");  
queue.add("Jai");  
queue.add("Rahul");  

System.out.println("head:"+queue.element());  
System.out.println("head:"+queue.peek());  

System.out.println("iterating the queue elements:");  
Iterator itr=queue.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
}  

queue.remove();  
queue.poll();  

System.out.println("after removing two elements:");  
Iterator itr2=queue.iterator();  
while(itr2.hasNext()){  
System.out.println(itr2.next());  
}  

}  
}  

Output:head:Amit
   head:Amit
   iterating the queue elements:
   Amit
   Jai
   Karan
   Vijay
   Rahul
   after removing two elements:
   Karan
   Rahul
   Vijay

Hi there i was trying to learn priority queue which comes under collections in java(shown above). Now i'm really confused, because of the output. I cant understand how the output came like this (which is shown above).

iterating the queue elements:
   Amit
   Jai
   Karan
   Vijay
   Rahul

how does vijay came before rahul? if its in alphabetical order rahul must come before vijay i guess.

so can anyone explain whats happening inside the program and method element() what does it do?. I couldnt find that method.


回答1:


PriorityQueue doesn't store the elements in sorted order, but it allows you to get the elements from it in sorted order. It just makes sure that the the element at the head is the least element as per the ordering used for it.

So, if you store multiple numbers - 2, 1, 4, 3, 6, 8, it will make sure that 1 is the next element you remove. Then when you remove 1, it moves 2 to head. It doesn't bother about the ordering of rest of the elements.




回答2:


Most of the time a priority queue is implemented using a heap datastructure. A heap is a tree which guarantees that

if A is parent of B , then A < B

It doesnt guarantee any other ordering. It is sufficient to provide the minimum element in constant time, to add an element in log time and to remove the key in log time.

It just happen that the iterator itr traverses the heap using a pre-order transversal.

Traverse(node)
   visit(node)
   Traverse(node.left())
   Traverse(node.right())

Which explains your result.

note: In java < is provided by implementing Comparable<T>




回答3:


This question is answered in the Javadoc:

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.

To traverse the PQ in sorted order you have to use the remove() method.



来源:https://stackoverflow.com/questions/22229154/iterating-through-priorityqueue-doesnt-yield-ordered-results

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