So, I was asked the following problem:
Write a program that creates a list of rationals and sorts them with increasing order. Use the appropriate methods from the Framework Collections classes to sort the items in ascending order.
I created a Rational class to represent rational numbers, and I also compiled a list of Rational random numbers. But it’s hard for me to understand how to implement a list sorting method. Here are the code samples before I go further:
public class Rational implements Comparable<Rational> {
private int num;
private int denom;
private int common;
public Rational() throws IllegalNumDenomException {
setNum(1);
setDenom(2);
}
public Rational(int num, int denom) throws IllegalNumDenomException {
common = gcd(num,denom);
setNum(num/common);
setDenom(denom/common);
}
public int compareTo(Rational rhs) {
int tempNumerator = this.getNum() * rhs.getDenom();
int tempNumeratorRhs = rhs.getNum() * this.getDenom();
if (tempNumerator < tempNumeratorRhs) {
return -1;
} else if (tempNumerator > tempNumeratorRhs) {
return 1;
}
return 0;
}
public String toString() {
return num + "/" + denom;
}
public int gcd(int x, int y) throws IllegalNumDenomException{
while(x != 1){
if(x == y){
return x;
}
else if(x>y){
return gcd(x-y,y);
}
return gcd(x,y/x);
}
return 1;
}
public class RationalList {
public static void main(String[] args) throws IllegalNumDenomException {
List<Rational> rationals = new ArrayList<Rational>();
Random rand = new Random();
int n = rand.nextInt(50) + 1;
for(int i = 1; i<10; i++){
rationals.add(new Rational(i,n));
n = rand.nextInt(50) + 1;
}
System.out.println("Original Order: " + rationals.toString());
sort(rationals);
System.out.println(rationals);
}
public static List<Rational> sort(List<Rational> rationals){
return rationals;
}
. compareTo, , Rational , . , , . , , Collections.sort() , . , .Array?
- , ? .