Results 1 to 1 of 1
 11212008, 02:46 PM #1Member
 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; } }
thanks
Chris
edit: dw, got it figured, thanks anyway!Last edited by linus_k; 11212008 at 03:03 PM.
Similar Threads

How to search with a Comparator
By Java Tip in forum java.langReplies: 0Last Post: 04152008, 07:39 PM 
How to write your own Comparator
By Java Tip in forum java.langReplies: 0Last Post: 04152008, 07:38 PM 
Using Comparable and Comparator interfaces
By barney in forum New To JavaReplies: 1Last Post: 08072007, 07:10 AM
Bookmarks