所以我遇到了以下问题:
编写一个程序,创建一个有理数列表并将它们按升序排序。使用 Collections Framework 类中的适当方法将元素按升序排序。
我创建了一个“Rational”类来表示有理数,并且我还制作了随机有理数列表。但是我很难找到一种方法来实现对列表进行排序的方法。在我继续之前,这里是代码示例:
public class Rational implements Comparable<Rational> {
private int num;
private int denom;
private int common;
// Default constructor initialises fields
public Rational() throws IllegalNumDenomException {
setNum(1);
setDenom(2);
}
// Constructor sets fields with given parameters
public Rational(int num, int denom) throws IllegalNumDenomException {
common = gcd(num,denom);
setNum(num/common);
setDenom(denom/common);
}
//Compares two rational numbers
public int compareTo(Rational rhs) {
int tempNumerator = this.getNum() * rhs.getDenom();
int tempNumeratorRhs = rhs.getNum() * this.getDenom();
//Compares rationalised numerators and returns a corresponding value
if (tempNumerator < tempNumeratorRhs) {
return -1;
} else if (tempNumerator > tempNumeratorRhs) {
return 1;
}
return 0;
}
// Overriden toString method
public String toString() {
return num + "/" + denom;
}
//Calculates the GCD of a fraction to simplify it later on
public int gcd(int x, int y) throws IllegalNumDenomException{
while(x != 1){ //Prevents infinite loop as everything is divisible by 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;
//Generates 9 random Rationals
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){
//Use compareTo method inside a loop until list is sorted
return rationals;
}
抱歉有点长。所以我的想法是创建一个排序方法并使用 compareTo 方法来确定 Rational 是否在正确的位置,如果没有交换它。但是我不确定你是否能够像在数组中一样在列表中移动元素。所以我想也许我需要实现 Collections.sort() 方法并覆盖 sort 方法,但我遇到了同样的问题。也许我可以使用 .toArray?
任何人都可以阐明如何做到这一点吗?只是提示会很有用。