javalistsortingcomparablerational-numbers

How to create a List of fractions?


I need a way of putting a fraction into an ArrayList. I am having problems however because I'm not sure how I could do this in a way that I could later compare them so they can be sorted.

Note: I will be using 4 or more fractions and I'm not too sure how to (if its possible) to use the comparable class to do it for more than 2.

For example: I need to input 1/1 , 3/4 , 7/4 , 2/8

I then need to sort them (Using the list) from the smallest to the greatest.

Any help is appreciated.


Solution

  • public class Fraction implements Comparable<Fraction> {
       private int x1, x2; // implement get/set
    
       public int compareTo(Fraction o) {
           double tmp = Math.abs((double)x1 / x2 - (double)o.x1 / o.x2);
           if (tmp < 0) return -1;
           if (tmp < 1e-9) return 0;
           return 1;
       }
    }
    

    Now:

    ArrayList<Fraction> f;
    Collections.sort(f);