Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 11-21-2008, 03:46 PM
Member
 
Join Date: Nov 2008
Posts: 5
Rep Power: 0
linus_k is on a distinguished road
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:
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.
Bookmark Post in Technorati
Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
How to search with a Comparator Java Tip java.lang 0 04-15-2008 08:39 PM
How to write your own Comparator Java Tip java.lang 0 04-15-2008 08:38 PM
Using Comparable and Comparator interfaces barney New To Java 1 08-07-2007 08:10 AM


All times are GMT +2. The time now is 03:42 PM.



VBulletin, Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Content Relevant URLs by vBSEO ©2009, Crawlability, Inc.
Copyright ©2006 - 2007, www.java-forums.org