user1741722
user1741722

Reputation: 49

Removing elements with the same priority from a PriorityQueue

While executing this code:

Queue q=new PriorityQueue();
q.add(1);
q.add(1);
q.add(1);
q.add(2);
System.out.println(q);
System.out.println(q.remove(1));
System.out.println(q);

The output is:

[1, 1, 1, 2]
true
[1, 2, 1]

Could someone please explain the reason for this shifting in the value of 1 in the output?

Upvotes: 2

Views: 418

Answers (1)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

This is because System.out.println(q); prints the elements returned by PriorityQueue.iterator and PriorityQueue API says

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

Upvotes: 3

Related Questions