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 );
}
}
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 );
}
}