comparator

D

Daniel

I am testing a Comparator with the PriorityQueue (JDK1.5), and I want it to
sort ascending. I tested several random numbers, and they work, but when I
added the number 100 or 1000 to the list, it did not sort right. Any help
appreciated.

Also, as a side note, I tried using PriorityQueue without a comparator and
the javadocs said it would sort to its natural order, but it did not (called
the iterator() and the list was unordered). Isn't it supposed to sort for
me?

Thanks!



package daniel.test;

import daniel.comparator.NumberAscComparator;

import java.util.PriorityQueue;

public class SmallestNumbers
{
public static void main( String[] args )
{
PriorityQueue q = new PriorityQueue( 10, new
NumberAscComparator() );
q.add( new Integer( 99 ) );
q.add( new Integer( 88 ) );
q.add( new Integer( 66 ) );
q.add( new Integer( 100 ) ); // this makes the list not sort
right
q.add( new Integer( 77 ) );
q.add( new Integer( 200 ) );

System.out.println( "original: " + q );


}
}

package daniel.comparator;

import java.util.Comparator;

public class NumberAscComparator implements Comparator
{
public int compare( Object o, Object o2 )
{
if ( !(o instanceof Integer ) || !(o2 instanceof Integer ) )
{
return 0;
}
Integer i = (Integer)o;
Integer i2 = (Integer)o2;

return i.compareTo( i2 );
}
}
 
J

John McGrath

I am testing a Comparator with the PriorityQueue (JDK1.5), and I want it
to sort ascending. I tested several random numbers, and they work, but
when I added the number 100 or 1000 to the list, it did not sort right.
Any help appreciated.

Also, as a side note, I tried using PriorityQueue without a comparator
and the javadocs said it would sort to its natural order, but it did not
(called the iterator() and the list was unordered). Isn't it supposed to
sort for me?

Try pulling the objects from the PriorityQueue using poll(). They are not
maintained in order, but they do come out in order.
 
D

Daniel

Thank you, poll() did it!

John McGrath said:
Try pulling the objects from the PriorityQueue using poll(). They are not
maintained in order, but they do come out in order.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top