How to understand PriorityQueue?

This question already has an answer here:

  • The built-in iterator for java's PriorityQueue does not traverse the data structure in any particular order. Why? 4 answers

Here is My Code

 import java.util.*;     public class PriorityPuzzle{         public static void main(String []args){             PriorityQueue<Integer> prq = new PriorityQueue<Integer>();               for ( int i = 10; i > 0; i-- ){                     prq.add (i);                    System.out.print(i+" , ");             }                System.out.println ( "\n Initial priority queue values are: "+ prq);             }       } 

Result

How to understand PriorityQueue?

I donnot know why the after Priority the queue become {1,2,5,4,3,9,6,10,7,8}

Replay

The toString() method for PriorityQueue just inherits the one from AbstractCollection. This just iterates over the items in the collection and prints them.

From the docs for the iterator of PriorityQueue:

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

So printing the queue doesn't print the items in the order that you would get them if you retrieved them from the queue one at a time.

The docs say that this priority queue is based on a priority heap. The docs also don't mention that toString() is overridden by this class. PriorityQueue actually uses the toString method from AbstractCollection.

I'm going to guess that therefore toString() doesn't bother to print the elements in order, it just uses some arbitrary internal order dependent on the heap. If you want to print the elements in order, you'll have to use an Iterator or something similar and print them yourself.

Category: java Time: 2016-01-16 Views: 0
Tags: java

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.127 (s). 12 q(s)