File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Priority Queue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Priority Queue" Watch "Priority Queue" New topic
Author

Priority Queue

Jitendra Jha
Ranch Hand

Joined: Jan 28, 2007
Posts: 91
The following method

void queues()
{
Comparator<String> c=new Comparator<String>(){public int compare(String a,String b){return b.compareTo(a);}};
Queue<String> qu=new PriorityQueue<String>(5,c);
String[] str={"The","Champ","Is","Here","Always"};
for(String s:str)
qu.offer(s);

System.out.println(qu);
System.out.println(qu.peek());
//System.out.println(qu.poll());
System.out.println(qu);
for(String as:qu)
System.out.println(as);


when this is compiled,i do not get a sorted queue.I am trying to get a sorting based on the reverse of natural order.
somebody please help

Thanks


Jitendra
SCJP1.5
SCWCD1.5
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Hi Jitendra,

Unlike List classes, Queue classes do not guarantee that their iterators return the elements in any particular order. toString() and the enhanced for loop depend on the iterator order.

To get the correct sorted order, you need to repeatedly poll() the queue until it's empty.


SCJP 5.0
Jitendra Jha
Ranch Hand

Joined: Jan 28, 2007
Posts: 91
Kelvin
Unlike List classes, Queue classes do not guarantee that their iterators return the elements in any particular order.


I agree but PriorityQueue is supposed to be sorted.That means it should arrange elements in a sorted order(Higher priority first in this case).
Secondly,i have also implemented Comparator,This should have done the trick.
Don't you agree???
Please help!!!

Thanks
Jari Timonen
Ranch Hand

Joined: Jan 16, 2004
Posts: 230
Correct usage of PriorityQueue is poll(), peek(), offer(E element). You should not use PQ if you just want to iterate through it.

From PQ API description:

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces. The Iterator provided in method iterator() is not guaranteed to traverse the elements of the PriorityQueue in any particular order. If you need ordered traversal, consider using Arrays.sort(pq.toArray()).


SCJP 5.0, SCJD URLyBird 1.3.3, OCMJEA 5 (SCEA) Factory Homes
Jitendra Jha
Ranch Hand

Joined: Jan 28, 2007
Posts: 91
That really explains a lot.
K&B mentions that PQ is sorted,hence i tried this code.
Thanks a million
 
jQuery in Action, 2nd edition
 
subject: Priority Queue
 
Similar Threads
PriorityQueue and ordering?
priority queue!
Generics
sorting backwards with Arrays.sort()
Priority queue