This week's giveaway is in the Spring forum.We're giving away four copies of Learn Spring Security (video course) and have Eugen Paraschiv on-line!See this thread for details.
Win a copy of Learn Spring Security (video course) this week in the Spring forum!

# priority queue!

vijay umar
Ranch Hand
Posts: 100
here is one code:

import java.util.*;
class PQ
{
static class PQsort
implements Comparator<Integer> {

public int compare(Integer one, Integer two) {
return two - one; // unboxing
}
}

public static void main(String[] args)
{
int[] ia = {1,5,3,7,6,9,8 }; // unordered data
PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>(); // use natural order
for(int x : ia) // load queue
pq1.offer(x);
for(int x : ia)
System.out.print(pq1.poll() + " ");
System.out.println("");
PQsort pqs = new PQsort(); // get a Comparator
PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10,pqs); // use Comparator
for(int x : ia) // load queue
pq2.offer(x);
System.out.println("size " + pq2.size());
System.out.println("peek " + pq2.peek());
System.out.println("size " + pq2.size());
System.out.println("poll " + pq2.poll());
System.out.println("size " + pq2.size());
for(int x : ia) // review queue
System.out.print(pq2.poll() + " ");
}
}

in this code i dint understand that how the comparator is working.How does it arrange the elements in the queue?
espicially this one:
[b]implements Comparator<Integer> {

public int compare(Integer one, Integer two) {
return two - one; // unboxing
}

armando fonseca
Ranch Hand
Posts: 49
hi vijay,
look this part carefully,

You are comparing two numbers by subtracting them!
if integer two > than integer one
then it return a positive number , zero if they are equal and a negative number if integer two is less than integer one. Using your code , it will order from highest to lowest if I'm not mistaken( I'm not sure!.... any the order is irrelevant). Then when you are adding the numbers at:
, it will use the sorting algorithm to store the values in the queue rather than using FIFO.
Now I have a question to you vijay, by looking your comparator implementation, is the output: 9,8,7,6,5,3,1 when traversing ?

-Armando

Ankit Garg
Sheriff
Posts: 9509
22

Shin Kudo
Greenhorn
Posts: 25
He wants to make the code look like in real SCJP exam

Ankit Garg
Sheriff
Posts: 9509
22
Shin Kudo wrote:He wants to make the code look like in real SCJP exam

In the real SCJP exam, the code has proper indentation. It's just that the code is jammed into the smallest size possible. So this code would come something like this

vijay umar
Ranch Hand
Posts: 100
hi armando ,

nice meeting you