# Thread: Use different comparator for SortedSet

1. Member
Join Date
Nov 2008
Posts
5
Rep Power
0

## 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:
Java 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!
Last edited by linus_k; 11-21-2008 at 04:03 PM.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•