Iterating through PriorityQueue doesn't yield ordered results

后端 未结 3 1077
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 00:56
import java.util.*;
class Priority{  
public static void main(String args[]){  

PriorityQueue queue=new PriorityQueue();  
queue.add(\"Amit\         


        
相关标签:
3条回答
  • 2021-01-25 01:33

    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.

    0 讨论(0)
  • 2021-01-25 01:42

    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.

    0 讨论(0)
  • 2021-01-25 01:46

    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>

    0 讨论(0)
提交回复
热议问题