3
public static void main(String[] a)     
{       
  Queue queue = new PriorityQueue();
  queue.add(44);
  queue.add(90);
  queue.add(9);
  queue.add(89);
  queue.add(45);
  queue.add(61);
  queue.add(1);
  System.out.println(queue);
}

output :- [1, 45, 9, 90, 89, 61, 44]

but output must be [1,9,44,45,61,89,90]

JHS
  • 7,761
  • 2
  • 29
  • 53
Nitesh
  • 107
  • 2
  • 6

3 Answers3

3

The elements will be retreived in sort order when you take them from the queue.

Try this:

public static void main(String[] a)
{
    Queue queue = new PriorityQueue();
    queue.add(44);
    queue.add(90);
    queue.add(9);
    queue.add(89);
    queue.add(45);
    queue.add(61);
    queue.add(1);
    System.out.println(queue.poll());
    System.out.println(queue.poll());
    System.out.println(queue.poll());
    System.out.println(queue.poll());
    System.out.println(queue.poll());
    System.out.println(queue.poll());
    System.out.println(queue.poll());
}
vikingsteve
  • 38,481
  • 23
  • 112
  • 156
1

I don't think toString() will output in any particular order. toString() is implemented using the AbstractCollection.toString(), and that uses the collection's iterator. From the PriorityQueue doc:

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

Note that this SO question may be of further use.

Community
  • 1
  • 1
Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

A queue (specifically a priority queue or priority heap) is not a list!

It's sorting does not mean that every element is sorted (or that you get any specific ordering).

It only means that whenever you poll() an element, it will be the smallest!

That could be achieved by storing a totally sorted list or (as it happens to be the case) by using a different, more efficient data structure: a heap.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614