Search code examples
javacollectionspriority-queue

How Integer Data get Inserted in Prioroty Queue(Sequence Not able to undestand)


I am learning Priority Queue of Java in Collection framework.

Currently I am on the topic called Priority Queue. I referred the following article and this video to learn, then I tested the code on IDE

int ar[] = {3, 5, 12, 9, 1};
PriorityQueue<Integer>  pq = new PriorityQueue<>();
for(int f:ar)
pq.add(f);

When I am printing pq iam getting [1, 3, 12, 9, 5]

How this sequence is arrange (What is the priority here?) I am not understanding, as it is not increasing order or decreasing order. please guide


Solution

  • PriorityQueue stores the elements in the natural order unless a Comparator is provided while creating the queue.

    int ar[] = {3, 5, 12, 9, 1};
    PriorityQueue<Integer>  pq = new PriorityQueue<>();
    for(int f:ar)
      pq.add(f);
    System.out.println(pq);
    

    The result is [1, 3, 12, 9, 5] as toString method of AbstractCollection class is called when you print the queue.

    public String toString() {
      Iterator<E> it = iterator();
      if (! it.hasNext())
        return "[]";
    
      StringBuilder sb = new StringBuilder();
      sb.append('[');
      for (;;) {
        E e = it.next();
        sb.append(e == this ? "(this Collection)" : e);
        if (! it.hasNext())
          return sb.append(']').toString();
        sb.append(',').append(' ');
      }
    }
    

    iterator() used here is implemented in the PriorityQueue class which does not return the elements in any particular order. Hence, when you print the priority queue, it prints the elements without any order.

    /**
     * Returns an iterator over the elements in this queue. The iterator
     * does not return the elements in any particular order.
     *
     * @return an iterator over the elements in this queue
     */
    public Iterator<E> iterator() {
        return new Itr();
    }
    

    If you want to know the order of elements stored in the queue, you have to poll elements and print them.

    int ar[] = {3, 5, 12, 9, 1};
    PriorityQueue<Integer>  pq = new PriorityQueue<>(ar.length);
    for(int f:ar)
      pq.add(f);
    
    while(!pq.isEmpty())
      System.out.println(pq.poll());
    

    this will give you elements in the order they are stored.

    1
    3
    5
    9
    12