Results 1 to 1 of 1
  1. #1
    linus_k is offline Member
    Join Date
    Nov 2008
    Rep Power

    Default 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;
            return 0;
    Any advice on how to do this without sending to an array and sorting that would be much appreciated

    edit: dw, got it figured, thanks anyway!
    Last edited by linus_k; 11-21-2008 at 03:03 PM.

Similar Threads

  1. How to search with a Comparator
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 07:39 PM
  2. How to write your own Comparator
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-15-2008, 07:38 PM
  3. Using Comparable and Comparator interfaces
    By barney in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 07:10 AM

Posting Permissions

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