0

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.

  • 2
    well can you show us what you already have? – washcloth Feb 16 '14 at 14:07
  • 1
    Do you want to preserve the original representation of the fraction, or is it okay if they are converted to a floating point number? – Michael Aaron Safyan Feb 16 '14 at 14:07
  • I don't really have much worth showing because this is the start of a project. And I need to preserve the representation for visual purposes but I guess it wouldn't make much of a difference if it was converted to work out the ordering. – user3006216 Feb 16 '14 at 14:11

3 Answers3

2

Create a class called Fraction which stores two variables: numerator and denominator. You can then make an ArrayList of Fractions.

If you'd like to sort them easily, your best bet is to have it implement Comparable.

GreySwordz
  • 368
  • 1
  • 9
1

You can do it two ways first you can take fractions as float value otherwise make a class representing the fraction value then make another class implement Interface Comparator.And then use Collections to sort.

Devavrata
  • 1,785
  • 17
  • 30
1
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);