سؤال

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

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);

نصائح أخرى

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.

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top