# Use different comparator for SortedSet

• 11-21-2008, 03:46 PM
linus_k
Use different comparator for SortedSet
Hi all, I'm pretty new to java so simple replies would be appreciated!

I've written a Rational class for storing numbers as exact fractions rather than decimal in their lowest terms, and I'm trying to create a sorted set of them using java.util.SortedSet, but I can't figure out how to declare the comparator so that java lets me create a sorted set of objects with no automatically defined ordering.

I've spent a while searching but can't find any useful resources that I understand on it, abbreviated code:
Code:

``` public class Main {     public static void main(String[] args) {         SortedSet<Rational> s = new TreeSet<Rational>();         //add elements, ..., output*     } } public class Rational {         long numerator, denominator;         public Rational (long num, long denom) {         long n = HCF(num, denom);         numerator = num / n;         denominator = denom / n;     }     public boolean bigger(Rational a, Rational b) {         double x, y;         x = a.toDouble(); y = a.toDouble();         return (x > y);     }     public double toDouble() {         double x = (double) ( this.numerator ) / (double) ( this.denominator );         return x;     }     public static long HCF(long m, long n) {         if (m == 0) return n;         if (n == 0) return m;         return HCF(n,m%n);     } } public class RationalComparator implements Comparator {     public int compare(Object rat1, Object rat2){     Rational x = (Rational) (rat1);     Rational y = (Rational) (rat2);     if( x.bigger(y) )         return 1;     else if( y.bigger(x) )         return -1;     else         return 0; } }```
Any advice on how to do this without sending to an array and sorting that would be much appreciated
thanks
Chris

edit: dw, got it figured, thanks anyway!