comparator



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



.



Relevant Pages

  • Re: comparator
    ... >> I am testing a Comparator with the PriorityQueue, ... >> to sort ascending. ... >> when I added the number 100 or 1000 to the list, it did not sort right. ...
    (comp.lang.java.programmer)
  • Re: comparator
    ... > I am testing a Comparator with the PriorityQueue, ... > to sort ascending. ... > when I added the number 100 or 1000 to the list, it did not sort right. ...
    (comp.lang.java.programmer)
  • Re: Sorting objects in ooRex? is this possible with data structures?
    ... The sorting features are modeled off of what Java does with its Comparable and Comparator classes. ... If you want to sort on different column positions, we have a Comparator class that allows you to specify the comparison colums. ... Here's one that compares strings as numbers: ...
    (comp.lang.rexx)
  • Re: How to sort String array A based on int array B
    ... String the other's an int. ... Then the Comparator has all it needs to sort -- the int. ...
    (comp.lang.java.help)
  • Re: indirect sort
    ... puts it into an array and sorts this array is faster than ... just sorting the objects. ... worthy to have my own implementation of sort(), ... comparator can simple subtract one argument from the other and cast ...
    (comp.lang.java.programmer)